码迷,mamicode.com
首页 > 其他好文 > 详细

解题报告 之 HDU5289 Assignment

时间:2015-08-13 15:54:37      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:acm   多校   hdu5289   

解题报告 之 HDU5289 Assignment


Description

Tom owns a company and he is the boss. There are n staffs which are numbered from 1 to n in this company, and every staff has a ability. Now, Tom is going to assign a special task to some staffs who were in the same group. In a group, the difference of the ability of any two staff is less than k, and their numbers are continuous. Tom want to know the number of groups like this.
 

Input

In the first line a number T indicates the number of test cases. Then for each case the first line contain 2 numbers n, k (1<=n<=100000, 0<k<=10^9),indicate the company has n persons, k means the maximum difference between abilities of staff in a group is less than k. The second line contains n integers:a[1],a[2],…,a[n](0<=a[i]<=10^9),indicate the i-th staff’s ability.
 

Output

For each test,output the number of groups.
 

Sample Input

2 4 2 3 1 2 4 10 5 0 3 4 5 2 1 6 7 8 9
 

Sample Output

5 28

Hint

First Sample, the satisfied groups include:[1,1]、[2,2]、[3,3]、[4,4] 、[2,3] 
         
 

题目大意:给你一个序列,1~n。问你有几个连续子序列满足其中最大值和最小值的差小于k。


分析:又是一道单调队列的题,我们设立两个指针i、j,从头开始往右移动,力求在O(n)的复杂度扫描一遍解决问题。单调队列的作用是什么呢,它是以很小的时间代价动态更新当前序列中的最大最小值。(此处如果有不懂请自行学习单调队列,此处只需要知道它动态更新最大最小值即可)。[j,i-1]表示当前关注的序列,我们将i指针一直向前,去更新最大最小值,直到[j,i]的最值之差>=k,说明此时的[j,i-1]是极限了。那么以 j 为起点的序列就只能从[j,i-1]选一个终点,有i-j种选法。然后j向前移动一位,重复以上过程,一直到 i 更新完整个序列。

上代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<deque>
using namespace std;

const int MAXN = 1e5 + 10;

int numbers[MAXN];

deque<int> high;
deque<int> low;

int main()
{
	int kase;
	cin >> kase;
	int n, k;
	while(kase--)
	{
		cin >> n >> k;
		for(int i = 1; i <= n; i++)
		{
			scanf( "%d", &numbers[i] );
		}
		high.clear();
		low.clear();

		int i, j; //i is pre pointer
		long long ans = 0;
		for(i = j = 1; i <= n; i++)
		{

			while(!high.empty() && high.back() < numbers[i]) high.pop_back();
			high.push_back( numbers[i] );

			while(!low.empty() && low.back() > numbers[i]) low.pop_back();
			low.push_back( numbers[i] );

			while(!high.empty() && !low.empty() && high.front() - low.front() >= k)
			{
				ans += i - j;
				if(high.front() == numbers[j]) high.pop_front();
				if(low.front() == numbers[j]) low.pop_front();
				//如果j已经前移出了最小值所在位置,则弹出
				j++;
			}
		}
		while(j <= n)
		//不要忘记
		{
			ans += i - j;
			j++;

		}

		cout << ans << endl;

	}
	return 0;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

解题报告 之 HDU5289 Assignment

标签:acm   多校   hdu5289   

原文地址:http://blog.csdn.net/maxichu/article/details/47612497

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!