lower_bound会找出序列中第一个大于等于x的数
upper_bound会找出序列中第一个大于x的数
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.
输入
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
输出
2
7
0
1
lower_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于或等于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
upper_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
#include <iostream>
#include <algorithm>
using namespace std;
#define int long long
int ch[205001];
signed main()
{
int t;
cin >> t;
while (t--)
{
int n, l, r;
cin >> n >> l >> r;
for (int i = 0; i < n; i++)
{
cin >> ch[i];
}
sort(ch, ch + n);
int sum = 0;
for (int i = 0; i < n; i++)
{
int a = lower_bound(ch + i + 1, ch + n, l - ch[i]) - ch;
int b = upper_bound(ch + i + 1, ch + n, r - ch[i]) - ch;
int c = b - a;
sum += c;
}
cout << sum << endl;
}
}

被折叠的 条评论
为什么被折叠?



