题意: 很简单 不再翻译
题解: 这道题可用二分也可用尺取解, 我这里使用的是二分解法
对于坐标我们先排序, 依次遍历, 对于每个坐标二分查找查找满足题意的下标, 同时使用右边界.
注意一般check函数中传参都使用mid
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
#define ms(x, n) memset(x,n,sizeof(x));
typedef long long LL;
const LL maxn = 1e5+10;
int T, n, k, x[maxn];
bool check(LL a, LL b){ return x[b]-x[a] <= k;}
int main()
{
cin >> T;
while(T--){
cin >> n >> k;
for(int i = 1; i <= n; i++)
cin >> x[i];
sort(x+1, x+1+n);
LL ans = 0;
for(LL i = 1; i < n; i++){
//二分查找最远的满足题意的下标
LL l = i+1, r = n;
while(l <= r){
LL mid = (l+r)/2;
if(check(i, mid)) l = mid+1;
else r = mid-1;
}
ans += (r-i);
}
cout << ans << endl;
}
return 0;
}