您的位置:首页 > 其它

hdu5289(2015多校1)--Assignment(单调队列)

2015-07-22 08:57 330 查看


Assignment

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

Total Submission(s): 503    Accepted Submission(s): 256


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]

题目大意:给出一个数列,问其中存在多少连续子序列,子序列的最大值-最小值<k

O(n)的时间复杂度,,,,单调队列太牛叉                              

用单调队列维护最大值最小值,双指针,第一个第二个指针初始指向第一个数据,第一个指针按顺序不断向队尾添加数据,当最大值最小值的差大于等于k后,就意味着新添加的这个不能作用于当前第二个指针的位置,也就能计算出,以第二个指针位置开始的连续子序列的个数,最后统计总和。

#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std ;
#define LL __int64
deque <LL> deq1 , deq2 ;
//单调队列,deq1最大值,deq2最小值
LL a[100010] ;
int main() {
int t , n , i , j ;
LL k , ans ;
scanf("%d", &t) ;
while( t-- ) {
scanf("%d %I64d", &n, &k) ;
for(i = 0 ; i < n ; i++)
scanf("%I64d", &a[i]) ;
if(k == 0) {
printf("0\n") ;
continue ;
}
while( !deq1.empty() ) deq1.pop_back() ;
while( !deq2.empty() ) deq2.pop_back() ;
for(i = 0 , j = 0 , ans = 0; i < n ; i++) {//i在前,j在后
while( !deq1.empty() && deq1.back() < a[i] ) deq1.pop_back() ;
deq1.push_back(a[i]) ;
while( !deq2.empty() && deq2.back() > a[i] ) deq2.pop_back() ;
deq2.push_back(a[i]) ;
while( !deq1.empty() && !deq2.empty() && deq1.front() - deq2.front() >= k ) {
ans += (i-j) ;
//printf("%d %d,%I64d %I64d\n", i , j, deq1.front() , deq2.front() ) ;
if( deq1.front() == a[j] ) deq1.pop_front() ;
if( deq2.front() == a[j] ) deq2.pop_front() ;
j++ ;
}
}
while( j < n ) {
ans += (i-j) ;
j++ ;
}
printf("%I64d\n", ans) ;
}
return 0 ;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: