对数组升序排序,枚举A
(A-B=C)问题转化为对于A在A之前找等于(A-C)的值的个数,可以用二分做
复杂度:(O(nlogn))
#include<iostream>
#include<algorithm>
using namespace std;
#define LL long long
const int N = 200010;
int a[N];
int n, c;
int main(){
cin >> n >> c;
for(int i = 1; i <= n; i ++) cin >> a[i];
sort(a + 1, a + n + 1);
LL res = 0;
for(int i = 2; i <= n; i ++){
int l = 1, r = i - 1, x = a[i] - c;
while(l < r){
int mid = l + r >> 1;
if(a[mid] >= x) r = mid;
else l = mid + 1;
}
if(a[l] == x){
int p = l;
l = 1, r = i - 1;
while(l < r){
int mid = l + r + 1 >> 1;
if(a[mid] <= x) l = mid;
else r = mid - 1;
}
if(a[l] == x) res += l - p + 1;
}
}
cout << res;
return 0;
}