HDU - 5289 Assignment

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;
}
全部评论

相关推荐

09-01 11:31
门头沟学院 Java
buul:七牛云的吧,感觉想法是好的,但是大家没那么多时间弄他这个啊。。。不知道的还以为他是顶尖大厂呢还搞比赛抢hc,只能说应试者的痛苦考察方是无法理解的,他们只会想一出是一出
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务