P1102 A-B数对题解
一、二分法解法
#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;
}
为什么想到用二分搜索?
遍历每一个数,与之相对的另一个数在数组中是否存在,如果存在的话,存在几个,就是这道题的核心。理解了这点,就知道是二分搜索了。
二、STL大法之MAP解法
#include <bits/stdc++.h>
using namespace std;
const int N = 200010;
typedef long long LL;
unordered_map<int, int> _map;
int a[N];
int n;
int c;
LL ans;
int main() {
cin >> n >> c;
for (int i = 1; i <= n; i++)cin >> a[i], _map[a[i]]++;
for (int i = 1; i <= n; i++)ans += _map[a[i] - c];
cout << ans << endl;
return 0;
}