Hdu-5289 Assignment (二分+RMQ || 单调队列)

来源:互联网 发布:rrt算法 编辑:程序博客网 时间:2024/05/01 13:47
Problem 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
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]
 

Author
FZUACM
 

Source
2015 Multi-University Training Contest 1

题意:给你一个数列,问你它有多少个子序列满足最大值-最小值小于k.


解法1:枚举起始位置,二分最大有效长度。


#include <cstdio>#include <iostream>#define max(a,b) (a) > (b) ? (a) : (b)#define min(a,b) (a) > (b) ? (b) : (a)using namespace std;int n,k,T,l[100005][30],r[100005][30],a[100005];int Log(int x){int num = 0;while(x){num++;x = x>>1;}return num-1;}int got(int x){return 1<<x;}int gotmax(int x,int y){int L = Log(y-x+1);return max(r[x][L],r[y-got(L)+1][L]);}int gotmin(int x,int y){int L = Log(y-x+1);return min(l[x][L],l[y-got(L)+1][L]);}bool check(int x,int y){if(gotmax(x,y)-gotmin(x,y) < k) return true;return false;}int main() {scanf("%d",&T);while(T--){scanf("%d %d",&n,&k);long long ans = 0;for(int i = 1;i <= n;i++) {scanf("%d",&a[i]);l[i][0] = a[i];r[i][0] = a[i];}for(int i = 1;got(i) <= n;i++) for(int j = 1;j+got(i)-1 <= n;j++)  {  l[j][i] = min(l[j][i-1],l[j+got(i-1)][i-1]);  r[j][i] = max(r[j][i-1],r[j+got(i-1)][i-1]);  } for(int i = 1;i <= n;i++){int s = i,t = n;while(s != t){int mid = (s+t)/2 + 1;if(check(i,mid)) s = mid;else t = mid-1;}ans += (s-i+1ll);}cout<<ans<<endl; }}



解法2:双端单调队列维护最大最小值。


#include <queue>#include <cstdio>#include <iostream>#include <algorithm>using namespace std;int n,k,a[100007],T;int main(){scanf("%d",&T);while(T--){long long ans = 0;deque <int> Max,Min;scanf("%d %d",&n,&k);for(int i = 1;i <= n;i++) scanf("%d",&a[i]);int j = 1;for(int i = 1;i <= n;i++){while(!Max.empty() && Max.front() < i) Max.pop_front();while(!Min.empty() && Min.front() < i) Min.pop_front();while(j <=n && (Max.empty() || (abs(a[Max.front()]-a[j]) < k && abs(a[Min.front()]-a[j]) < k))){while(!Max.empty() && a[Max.back()] <= a[j]) Max.pop_back();while(!Min.empty() && a[Min.back()] >= a[j]) Min.pop_back();Max.push_back(j);Min.push_back(j);j++;}ans += j-i;}cout<<ans<<endl;}}




0 0