https://www.luogu.com.cn/problem/CF1762F
#include
using namespace std;
#define int long long
inline int read(){int x=0,f=1;char ch=getchar(); while(ch<'0'||
ch>'9'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9'){
x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}return x*f;}
#define Z(x) (x)*(x)
#define pb push_back
//mt19937 rand(time(0));
//mt19937_64 rand(time(0));
//srand(time(0));
#define N 500010
//#define M
//#define mo
struct node {
int x, id;
bool operator < (const node &A) const {
return id < A.id;
}
}b[N];
int n, m, i, j, k, T;
int ans, a[N], mp[N], nxt[N], f[N], l;
set<node>s;
set<node>::iterator it;
struct Binary_tree {
int cnt[N];
void add(int x, int y) {
while(x<N) cnt[x]+=y, x+=x&-x;
}
int que(int x) {
int ans = 0; while(x) ans+=cnt[x], x-=x&-x;
return ans;
}
}Bin;
void calc() {
for(i=1; i<=n; ++i) b[i].x = a[i], b[i].id = i;
auto cmp = [&] (node x, node y) -> bool {
if(x.x == y.x) return x.id > y.id;
return x.x > y.x;
};
sort(b+1, b+n+1, cmp);
s.clear();
for(i=l=1; i<=n; ++i) {
while(b[l].x>b[i].x+k) s.erase(b[l]), ++l;
it = s.upper_bound({0, b[i].id});
if(it == s.end()) nxt[b[i].id] = 0;
else nxt[b[i].id] = (it -> id);
s.insert(b[i]);
}
// for(i = 1; i <= n; ++i) printf("%d ", nxt[i]); printf("\n");
for(i=n; i>=1; --i) {
j=nxt[i];
f[i]=f[j]+1;
if(nxt[i]==0) f[i]+=Bin.que(a[i]+k)-Bin.que(a[i]-1);
else f[i]+=Bin.que(a[nxt[i]]-1)-Bin.que(a[i]-1);
ans+=f[i]; Bin.add(a[i], 1);
// printf("%lld (%lld %lld)", f[i], f[j]);
}
// printf("\n");
for(i=1; i<=n; ++i) Bin.add(a[i], -1);
}
signed main()
{
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
T=read();
while(T--) {
n=read(); k=read(); ans=0;
for(i=1; i<=n; ++i) {
a[i]=read(), mp[a[i]]++, ans-=mp[a[i]];
}
// printf("> %lld\n", ans); `
calc();
reverse(a+1, a+n+1);
calc();
for(i=1; i<=n; ++i) mp[a[i]]=0;
printf("%lld\n", ans);
}
return 0;
}