您的位置:首页 > 大数据 > 人工智能

2015 Multi-University Training Contest 1 Hdu 5289 Assignment

2015-07-21 19:53 405 查看


Assignment

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)

Total Submission(s): 148    Accepted Submission(s): 71


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
(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
HintFirst Sample, the satisfied groups include:[1,1]、[2,2]、[3,3]、[4,4] 、[2,3]

 

Source

2015 Multi-University Training Contest 1

 

题意:给n个数序列,问连续的区间[l,r]有多少个,区间[l,r]满足任意两个数的绝对值|Ai-Aj|<k
方法:因为数的规模,10w,不能枚举区间,那么枚举A[i],维护前面区间的最大最小值,通过这个计算区间数,累加。
维护始终是弱项!!!
#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
#define LL long long
LL n,k;
LL a[100001];
LL q1[100001];  //保存递增的下标i,维护单调递增a[i]
LL q2[100001];  //保存递增的下表i,维护单调递减a[i]
int main(){
freopen("data.out","w",stdout);
LL T;
cin>>T;
while(T--){
cin>>n>>k;
for(int i=0;i<n;i++)
cin>>a[i];
int l1,r1,l2,r2;
l1=r1=l2=r2=0;
int pre=0;
LL ans=0;
q1[0]=0;    //初始化队列
q2[0]=0;
for(int i=1;i<n;i++){
while(l1<=r1&&a[q1[r1]]>a[i])r1--;
q1[++r1]=i;     //维护队列
while(l2<=r2&&a[q2[r2]]<a[i])r2--;
q2[++r2]=i;
//当i仍然是满足group定义就不执行while,继续for i++
while(a[i]-a[q1[l1]]>=k||a[q2[l2]]-a[i]>=k){
//当i不满足group定义的时候,前面[pre,i)是满足的。
ans += i - pre;//[pre,i)
pre++;
while(q1[l1]<pre)l1++;
while(q2[l2]<pre)l2++;
}
cout<<"pre= "<<pre<<" a[i]= "<<a[i]<<endl;
cout<<"q1= ";for(int j=l1;j<=r1;j++)cout<<q1[j]<<" ";cout<<endl;
cout<<"q2= ";for(int j=l2;j<=r2;j++)cout<<q2[j]<<" ";cout<<endl;

}
//最后一个区间[pre,n)共n-pre个,但是[i,i]区间也算一个所以是(n-pre+1)*(n-pre)/2
ans += (n-pre+1)*(n-pre)/2;
cout<<ans<<endl;
}
return 0;
}


0 3 4 5 2 1 6 7 8 9

pre= 0 a[i]= 3

q1= 0 1 

q2= 1 

pre= 0 a[i]= 4

q1= 0 1 2 

q2= 2 

pre= 1 a[i]= 5

q1= 1 2 3 

q2= 3 

pre= 1 a[i]= 2

q1= 4 

q2= 3 4 

pre= 1 a[i]= 1

q1= 5 

q2= 3 4 5 

pre= 6 a[i]= 6

q1= 6 

q2= 6 

pre= 6 a[i]= 7

q1= 6 7 

q2= 7 

pre= 6 a[i]= 8

q1= 6 7 8 

q2= 8 

pre= 6 a[i]= 9

q1= 6 7 8 9 

q2= 9 

28
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息