跳到正文

题解

题解:CF1538C Number of Pairs

kfc444约 4 分钟
原文

这是 2026年10月21日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年10月20日
收录
2026年10月21日
更新
2026年11月11日
篇幅
约 4 分钟
题目
CF1538C

版本

  1. v2当前
  2. v1

CF1538C Number of Pairs 题解

题目传送门

描述

给定一个序列 aa 和两个数 l,rl, r,让你选择在序列中满足 l≤ai+aj≤rl \leq a_i+a_j \leq r 的数对的个数。

思路

先考虑暴力,可以枚举每个 ai,aja_i, a_j,时间复杂度 O(n2)O(n^2),很明显过不了。 接着考虑 O(nlogn)O(nlogn) 做法。可以先对数组进行排序,这样对于每个 aia_i,其在原序列中的答案一定是连续的。 所以我们可以用二分来查找其答案最左边的数,即大于等于 l−ail-a_i 的第一个数,记为 ldex⁡\operatorname{ldex},接着查找最右边的数,即小于等于 r−air-a_i 的最后一个数,记为 rdex⁡\operatorname{rdex}。 所以对于每个 aia_i 的答案即为 rdex⁡−ldex⁡+1\operatorname{rdex}-\operatorname{ldex}+1,总答案对其累加即可。 代码实现有两种方法,一种为手动写二分,一种是用 lower_bound⁡\operatorname{lower\_bound} 与 upper_bound⁡\operatorname{upper\_bound} 内置函数,这里两种方法的代码都给出来。

code 1
C++
#include <bits/stdc++.h>
using namespace std;

#define int long long
#define re register
#define code ios::sync_with_stdio(false);
#define by cin.tie(nullptr);
#define lzacode cout.tie(nullptr);

int a[210101];

signed main()
{
	code by lzacode
	int t;
	cin >> t;
	while (t--)
	{
		int n, x, y;
		cin >> n >> x >> y;
		for (int i = 1; i <= n; i++)
		{
			cin >> a[i];
		}
		sort(a+1, a+1+n);
		int ans=0;
		for (int i = 1; i <= n; i++)
		{
			int l=i+1, r=n, ldex=1e9, rdex=-1e9;
			while (l<=r)
			{
				int mid=(l+r)/2;
				if (a[i]+a[mid]<x) l=mid+1;
				else if (a[i]+a[mid]>y) r=mid-1;
				else
				{
					ldex=mid;
					r=mid-1;
				} 
			}
			l=i+1, r=n;
			while (l<=r)
			{
				int mid=(l+r)/2;
				if (a[i]+a[mid]<x) l=mid+1;
				else if (a[i]+a[mid]>y) r=mid-1;
				else
				{
					rdex=mid;
					l=mid+1;
				} 
			}
			if (ldex==1e9&&rdex==-1e9) continue;
			ans+=rdex-ldex+1; 
		}
		cout << ans << endl;
	}
	return 0;
}
code 2
C++
#include <bits/stdc++.h>
using namespace std;

#define int long long
#define re register
#define code ios::sync_with_stdio(false);
#define by cin.tie(nullptr);
#define lzacode cout.tie(nullptr);

int a[210101];

signed main()
{
	code by lzacode
	int t;
	cin >> t;
	while (t--)
	{
		int n, x, y;
		cin >> n >> x >> y;
		for (int i = 1; i <= n; i++)
		{
			cin >> a[i];
		}
		sort(a+1, a+1+n);
		a[n+1]=0x3f3f3f3f;
		int ans=0;
		for (int i = 1; i <= n; i++)
		{
			int ldex=lower_bound(a+i+1, a+n+2, x-a[i])-a;
			int rdex=upper_bound(a+i+1, a+n+2, y-a[i])-a;
			rdex--;
			if (rdex>=ldex) ans+=rdex-ldex+1;
		}
		cout << ans << endl;
	}
	return 0;
}