Files
python/TangDou/LuoGuBook/P1102.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

41 lines
1.1 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
const int N = 200010;
int a[N];
int c;
typedef long long LL;
LL cnt;
int main() {
int n;
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;
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;
}
//如果left存在那么right也一定存在大不了left=right嘛
if (left) right = l;
//左右端点差就是个数
if (left) cnt += right - left + 1;//right==left,那就是1个
}
printf("%lld", cnt);
return 0;
}