Assignment
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 5590 Accepted Submission(s): 2574
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],…,an,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]
我们可以知道,我们每次要找到一个最大的满足条件的区间,然后我们枚举左端点即可,然后对右端点二分,就能就出最长满的的区间了,然后区间长度就是这个点为左端点的贡献。
这道题卡线段树了,要用ST表查询。
AC代码:
#pragma GCC optimize(2)
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e5+10;
int T,n,k,a[N],res,mx[N][30],mi[N][30];
void st(){
for(int i=1;i<=n;i++) mx[i][0]=mi[i][0]=a[i]; int l=log(n)/log(2)+1;
for(int i=1;i<l;i++)
for(int j=1;j<=n-(1<<i)+1;j++){
mx[j][i]=max(mx[j][i-1],mx[j+(1<<(i-1))][i-1]);
mi[j][i]=min(mi[j][i-1],mi[j+(1<<(i-1))][i-1]);
}
}
inline int ask(int l,int r){
int k=log(r-l+1)/log(2);
return max(mx[l][k],mx[r-(1<<k)+1][k])-min(mi[l][k],mi[r-(1<<k)+1][k]);
}
signed main(){
cin>>T;
while(T--){
scanf("%lld %lld",&n,&k); res=0;
for(int i=1;i<=n;i++) scanf("%lld",&a[i]); st();
for(int i=1;i<=n;i++){
int l=i,r=n;
while(l<r){
int mid=l+r+1>>1;
if(ask(i,mid)<k) l=mid;
else r=mid-1;
}
res+=(l-i+1);
}
printf("%lld\n",res);
}
return 0;
}