codeforces 1538C Number of Pairs

对于一个数,我们要找与他相加<=r&&>=l的对的个数,我们设要ll为确保其>=l的最小数,rr为确保其<=r的最大数,显然,我们对数组排序后,这两个中间的数都满足条件。
学习lower_bound和upper_bound二分搜索就使码量非常小。
对于一个x,要查找他后面的序列,否则则会(1,3)(3,1)这样造成重复。

#include<bits/stdc++.h>
#define int  long long
#define Endl '\n'
#define endl '\n'
#define x first
#define y second
#define pi pair<int ,int>

using namespace std;

int a[200005];

signed main()
{
	int t;
	cin>>t;
	while(t--)
	{
		int n,l,r,aa,bb,cc;
		cin>>n>>l>>r;
		for(int i=0; i<n; i++)
		{
			cin>>a[i];
		}
		sort(a,a+n);
		int ans=0;
		for(int x=0; x<n; x++)
		{
			int ll=l-a[x];
			int rr=r-a[x];
			int lpos=lower_bound(a+x+1,a+n,ll)-a;//第一个大于等于要大于的,要从后一个开始搜 
			int rpos=upper_bound(a+x+1,a+n,rr)-a;//第一个不可以的 
			//cout<<x<<' '<<lpos<<' '<<rpos<<endl;
			ans+=rpos-lpos;
		}
		cout<<ans<<endl;

	}
	return 0;
}















评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值