1.二分查找B = A - C
#include<bits/stdc++.h>
using namespace std;
const int N = 200010;
long long q[N], c, res;
int n;
int main()
{
cin >> n >> c;
for(int i = 0; i < n; i ++ ) scanf("%d", &q[i]);
sort(q, q + n);
for(int i = 0; i < n; i ++ ){
if(q[i] <= c) continue;
int l = 0, r = i - 1, x = q[i] - c;
while(l < r){
int mid = (l + r) / 2;
if(q[mid] >= x) r = mid;
else l = mid + 1;
}
if(q[l] != x) continue;
int lr = l;
r = i - 1;
while(l < r){
int mid = (l + r + 1) / 2;
if(q[mid] <= x) l = mid;
else r = mid - 1;
}
// printf("%d %d %d\n", x, lr, l);
res = res + r - lr + 1;
}
cout << res;
}
2.哈希(手写开放寻址法有一个测试点tle)
#include<bits/stdc++.h>
using namespace std;
const int N = 200010;
long long c, q[N], res;
int n;
map<long long, long long> mp;
int main()
{
cin >> n >> c;
for(int i = 0; i < n; i ++ ){
cin >> q[i];
mp[q[i]] ++;
}
for(int i = 0; i < n; i ++ ){
res += mp[q[i] - c];
}
cout << res;
}
3.离散化
#include<bits/stdc++.h>
using namespace std;
const int N = 200010;
long long c, q[N], s[N], res;
int n;
vector<long long> all;
int find(int x)
{
int l = 0, r = all.size() - 1;
while(l < r){
int mid = (l + r) / 2;
if(all[mid] >= x) r = mid;
else l = mid + 1;
}
if(all[l] == x) return l;
else return -1;
}
int main()
{
cin >> n >> c;
for(int i = 0; i < n; i ++ ){
scanf("%lld", &q[i]);
all.push_back(q[i]);
}
sort(all.begin(), all.end());
all.erase(unique(all.begin(), all.end()), all.end());
for(int i = 0; i < n; i ++ ) s[find(q[i])] ++;
for(int i = 0; i < n; i ++){
int t = s[find(q[i] - c)];
if(t != -1) res += t;
}
cout << res;
}