题目链接
链接: P1102 A-B 数对
题目描述
解题思路
二分查找的两个模板
可以看另一篇文章 Acwing 二分查找复习 两种模板的比较和使用场景
代码实现
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
#include<deque>
#include<numeric>
#include<cmath>
#define _for(i,a,b) for(int i=(a);i<(b);i++)
#define _rep(i,a,b) for(int i=(a);i<=(b);i++)
typedef long long LL;
using namespace std;
const int N = 200001;
LL n,a[N],c,res;
int main()
{
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> n >> c;
_for(i, 0, n) cin >> a[i];
sort(a, a + n);
for (int i = n - 1; i >= 0; i--)
{
if (a[i] <= c) continue;
LL l = 0, r = n - 1, ll = 0, rr = n - 1,d=a[i]-c;
while (l < r)//寻找左端点
{
LL mid = (l + r) >> 1;
if (a[mid] >= d) r = mid;
else l = mid + 1;
}
if (a[l] != d) {
continue;
}
else {
while (ll < rr)//寻找右端点
{
LL mid = (ll + rr + 1) >> 1;
if (a[mid] <= d) ll = mid;
else rr = mid - 1;
}
}
res+=rr - l + 1;
}
cout<<res;
return 0;
}
总结
熟练掌握了二分的两种模板和应用场景