洛谷P1102
P1102 A-B 数对
这是《深入浅出(进阶)》的第一道题,早前自己做过
点击查看代码
#include<bits/stdc++.h>
using namespace std;
int main() {
int n, c; cin >> n >> c;
vector<int>e(n);
long long ans = 0;
for(int i = 0; i < n; i++) {
cin >> e[i];
}
sort(e.begin(), e.end());//单调性便于查找
for(int i = 0; i < n; i++) {
int a = e[i] + c;//A - B = C, 反推A = B + C
auto st = lower_bound(e.begin(), e.end(), a);
auto ed = upper_bound(e.begin(), e.end(), a);
if(st == e.end()) continue;//没找着A
ans += (int)(ed - st)//找到了都是A的区间
}
cout << ans << '\n';
return 0;
}

浙公网安备 33010602011771号