题目传送门
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 200010;
int a[N];
int n, c;
LL cnt; //累加和不加long long 死翘翘
int main() {
//输入
cin >> n >> c;
for (int i = 1; i <= n; i++) cin >> a[i];
//排序
sort(a + 1, a + 1 + n);
//遍历每一个数字
for (int i = 1; i < n; i++) {
//每个数字可能都是多个,我们不能漏掉每个数字
int left = 0, right = 0;
//左端点
int l = 1, r = n, k = a[i] + c;//k为目标值
while (l < r) {
int mid = (l + r) >> 1;
if (a[mid] >= k)r = mid;
else l = mid + 1;
}
if (a[l] == k)left = l;
//右端点
l = 1, r = n;
while (l < r) {
int mid = (l + r + 1) >> 1;
if (a[mid] <= k)l = mid;
else r = mid - 1;
}
if (a[l] == k) right = r;
//左右端点差就是个数,其实left如果不是0,那么right肯定不是0
if (left && right) cnt += right - left + 1;
}
//输出结果
printf("%lld", cnt);
return 0;
}