HDU-5289(单调队列)

来源:互联网 发布:中国报学史读后感知乎 编辑:程序博客网 时间:2024/06/05 18:41

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:a11,a22,…,ann(0<=aii<=10^9),indicate the i-th staff’s ability.
Output
For each test,output the number of groups.
Sample Input
24 23 1 2 410 50 3 4 5 2 1 6 7 8 9
Sample Output
528          
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<math.h>#include<stdio.h>#include<iostream>#include<deque>#include<string.h>using namespace std;int num[100005];int main(){int t;cin >> t;deque<int>high;deque<int>low;int n, k;long long int ans;while (t--){ans = 0;high.clear();low.clear();cin >> n >> k;for (int i = 1; i <= n; i++){scanf("%d", &num[i]);}int i, j;for (j = i = 1; i <= n; i++){while (!high.empty() && high.back() < num[i])high.pop_back();high.push_back(num[i]);while (!low.empty() && low.back() > num[i])low.pop_back();low.push_back(num[i]);while (!high.empty() && !low.empty() && (high.front() - low.front() >= k)){ans += i - j;if (high.front() == num[j])high.pop_front();if (low.front() == num[j])low.pop_front();j++;}}while (j <= n){ans += i - j;j++;}cout << ans << endl;}return 0;}



原创粉丝点击