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 28
#include <cstdio>
#include <map>
#include <iostream>
#include<cstring>
#include<bits/stdc++.h>
#define ll long long int
#define M 6
using namespace std;
inline ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
inline ll lcm(ll a,ll b){return a/gcd(a,b)*b;}
int moth[]={,,,,,,,,,,,,};
int dir[][]={, ,, ,-, ,,-};
int dirs[][]={, ,, ,-, ,,-, -,- ,-, ,,- ,,};
const int inf=0x3f3f3f3f;
const ll mod=1e9+;
int a[];
int maxn[][],minn[][];
void preST(int n){
for(int i=;i<=n;i++){
maxn[i][]=a[i];
minn[i][]=a[i];
}
int m=log(n)/log()+;
for(int j=;j<m;j++)
for(int i=;i<=(n-(<<j)+);i++){
maxn[i][j]=max(maxn[i][j-],maxn[i+(<<(j-))][j-]);
minn[i][j]=min(minn[i][j-],minn[i+(<<(j-))][j-]);
}
}
int queryST1(int l,int r){
int k=log(r-l+)/log();
return max(maxn[l][k],maxn[r-(<<k)+][k]);
}
int queryST2(int l,int r){
int k=log(r-l+)/log();
return min(minn[l][k],minn[r-(<<k)+][k]);
}
int main(){
//ios::sync_with_stdio(false);
int t;
scanf("%d",&t);
while(t--){
int n,k;
scanf("%d%d",&n,&k);;
for(int i=;i<=n;i++)
scanf("%d",&a[i]);;
preST(n);
ll ans=;
int l,r;
for(int i=;i<=n;i++){
int pos;
l=i; r=n;
while(l<=r){
int mid=(l+r)>>;
int mm=queryST1(i,mid);
int nn=queryST2(i,mid);
if(mm-nn<k){
l=mid+;
pos=mid;
}
else r=mid-;
}
ans+=(l-i);
}
printf("%lld\n",ans);
}
}