
代码实现
cpp
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 2e5 + 10;
unordered_map <int, int> a;
int cnt, n, c, b[N];
signed main()
{
cin >> n >> c;
for (int i = 1; i <= n; i++)
{
cin >> b[i];
a[b[i]]++;
}
for (int i = 1; i <= n; i++)
{
cnt += a[b[i] + c];
}
cout << cnt << endl;
return 0;
}
cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 2e5 + 10;
LL cnt, n, c, b[N];
int main()
{
cin >> n >> c;
for (int i = 1; i <= n; i++) cin >> b[i];
// 预处理 有序
sort(b+1, b+n+1);
for (int i = 1; i <= n; i++)
{
LL x = b[i] + c;
auto l = lower_bound(b + 1, b + n + 1, x);
auto r = upper_bound(b + 1, b + n + 1, x);
cnt += (r - l);
}
cout << cnt << endl;
return 0;
}