二分查找 P1102 A-B 数对


题目链接

链接: 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;
}

总结

熟练掌握了二分的两种模板和应用场景

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值