Assignment
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 4288 Accepted Submission(s): 1971
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
2 4 2 3 1 2 4 10 5 0 3 4 5 2 1 6 7 8 9
Sample Output
5 28HintFirst Sample, the satisfied groups include:[1,1]、[2,2]、[3,3]、[4,4] 、[2,3]
Author
FZUACM
Source
题意:问有多少个子区间极差小于k。
思路:枚举左端点,二分右端点即可,极值从st表取出。
# include <iostream>
# include <cstdio>
# include <cstring>
using namespace std;
typedef long long LL;
const int maxn = 1e5+3;
int n, k, a[maxn];
int mi[21][maxn], mx[21][maxn], tlog[maxn], p[21];
void init()
{
p[0] = 1;tlog[0] = -1;
for(int i=1; i<21; ++i) p[i] = p[i-1]*2;
for(int i=1; i<=n; ++i) tlog[i] = (i&(i-1))?tlog[i-1]:(tlog[i-1]+1);
for(int i=1; i<=n; ++i) mi[0][i] = a[i], mx[0][i] = a[i];
for(int i=1; p[i]<=n; ++i)
for(int j=1; j+p[i]-1<=n; ++j)
{
mi[i][j] = min(mi[i-1][j], mi[i-1][j+p[i-1]]);
mx[i][j] = max(mx[i-1][j], mx[i-1][j+p[i-1]]);
}
}
int get_mx(int l, int r)
{
int k = tlog[r-l+1];
return max(mx[k][l], mx[k][r-p[k]+1]);
}
int get_mi(int l, int r)
{
int k = tlog[r-l+1];
return min(mi[k][l], mi[k][r-p[k]+1]);
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&k);
for(int i=1; i<=n; ++i) scanf("%d",&a[i]);
init();
LL ans = 0;
for(int i=1; i<=n; ++i)
{
int l=i+1, r=n;
while(l<=r)
{
int m = l+r>>1;
if((LL)get_mx(i,m)-(LL)get_mi(i,m) < k) l=m+1;
else r = m-1;
}
ans += r-i+1;
}
printf("%lld\n",ans);
}
return 0;
}