题意:给n个数字,问有多少区间[i, j](i <= j)满足区间中最大数与最小数差值小于k。
思路:从左起依次寻找能到达的最右端的区间,答案累加 r - l。
#include <cstdio>
#include <cstring>
const int M = 100005;
inline int max(int a, int b){
return a > b ? a : b;
}
inline int min(int a, int b){
return a < b ? a : b;
}
#define MAX true
#define MIN false
struct Tree{
int l, r, maxval, minval;
}tree[M * 4];
int nums[M], n, k;
void pullup(int rt){
tree[rt].maxval = max(tree[rt * 2].maxval, tree[rt * 2 + 1].maxval);
tree[rt].minval = min(tree[rt * 2].minval, tree[rt * 2 + 1].minval);
}
void buildtree(int rt, int l, int r) {
tree[rt].l = l, tree[rt].r = r;
if(l == r){
tree[rt].maxval = tree[rt].minval = nums[l];
return ;
}
int mid = (l + r) / 2;
buildtree(rt * 2, l, mid);
buildtree(rt * 2 + 1, mid + 1, r);
pullup(rt);
}
int query(int rt, int l, int r, bool flag){
if(tree[rt].l == l && tree[rt].r == r) {
return flag ? tree[rt].maxval : tree[rt].minval;
}
int mid = (tree[rt].l + tree[rt].r) / 2;
if(r <= mid) return query(rt * 2, l, r, flag);
else if(l > mid) return query(rt * 2 + 1, l, r, flag);
else {
if(flag) return max(query(rt * 2, l, mid, flag), query(rt * 2 + 1, mid + 1, r, flag));
else return min(query(rt * 2, l, mid, flag), query(rt * 2 + 1, mid + 1, r, flag));
}
}
int Scan() //输入外挂
{
int res=0,ch,flag=0;
if((ch=getchar())=='-')
flag=1;
else if(ch>='0'&&ch<='9')
res=ch-'0';
while((ch=getchar())>='0'&&ch<='9')
res=res*10+ch-'0';
return flag?-res:res;
}
main() {
int t;
// freopen("in.txt", "r", stdin);
scanf("%d", &t);
while(t--){
memset(tree, 0, sizeof tree);
scanf("%d %d", &n, &k);
for(int i = 1; i <= n; i++) nums[i] = Scan();
nums[n + 1] = 0x7fffffff;
n++;
buildtree(1, 1, n);
int i = 1, j = 1, minval = nums[1], maxval = nums[1];
long long ans = 0;
while(true){
while(maxval - minval < k && j < n) {
j++;
minval = min(minval, nums[j]);
maxval = max(maxval, nums[j]);
}
ans += j - i;
i++;
if(i == n) break;
maxval = query(1, i, j, MAX);
minval = query(1, i, j, MIN);
}
printf("%I64d\n", ans);
}
}