概述
C. Number of Pairs
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
You are given an array aa of nn integers. Find the number of pairs (i,j)(i,j) (1≤i<j≤n1≤i<j≤n) where the sum of ai+ajai+aj is greater than or equal to ll and less than or equal to rr (that is, l≤ai+aj≤rl≤ai+aj≤r).
For example, if n=3n=3, a=[5,1,2]a=[5,1,2], l=4l=4 and r=7r=7, then two pairs are suitable:
- i=1i=1 and j=2j=2 (4≤5+1≤74≤5+1≤7);
- i=1i=1 and j=3j=3 (4≤5+2≤74≤5+2≤7).
Input
The first line contains an integer tt (1≤t≤1041≤t≤104). Then tt test cases follow.
The first line of each test case contains three integers n,l,rn,l,r (1≤n≤2⋅1051≤n≤2⋅105, 1≤l≤r≤1091≤l≤r≤109) — the length of the array and the limits on the sum in the pair.
The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109).
It is guaranteed that the sum of nn overall test cases does not exceed 2⋅1052⋅105.
Output
For each test case, output a single integer — the number of index pairs (i,j)(i,j) (i<ji<j), such that l≤ai+aj≤rl≤ai+aj≤r.
Example
input
Copy
4 3 4 7 5 1 2 5 5 8 5 1 2 4 3 4 100 1000 1 1 1 1 5 9 13 2 5 5 1 1
output
Copy
2 7 0 1
题目有个把人带坑的点,那就是i<j,让人不敢排序,其实仔细一想,排序之后,a与a之间只存在大小关系,原顺序关系根本不需要;假设前面的原编号大于后面的,那前面的做j就行,反之亦然。谁做i,j都一样,这里的i<j只是让你不要重复选择(i,j)(j,i)而已.
排好序之后,对于每一个a[i],要找l-a[i]到r-a[i]的数量,lower_bound找到第一个大于等于l-a[i]的位置
upper_bound找到第一个大于r-a[i]的位置(前一个必定在合理范围内)
为了防止重复,即a[i]能找到l-a[i]与r-a[i]之间的数字,那么之后的也能找到a[i],所以从i+1开始找。
#include<iostream>
# include<cstring>
# include<algorithm>
# include<math.h>
# include<cmath>
# include<map>
using namespace std;
typedef long long int ll;
ll a[100000*2+10];
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
ll l,r;
scanf("%d%lld%lld",&n,&l,&r);
for(int i=1; i<=n; i++)
{
scanf("%lld",&a[i]);
}
sort(a+1,a+1+n);
ll sum=0;
for(int i=1; i<=n; i++)
{
ll cnt1=lower_bound(a+i+1,a+1+n,l-a[i])-a;
ll cnt2=upper_bound(a+i+1,a+1+n,r-a[i])-a;
sum+=(cnt2-cnt1);
}
cout<<sum<<'n';
}
}
最后
以上就是合适手套为你收集整理的C. Number of Pairs-Codeforces Round #725 (Div. 3)的全部内容,希望文章能够帮你解决C. Number of Pairs-Codeforces Round #725 (Div. 3)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复