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 a� of n� integers. Find the number of pairs (i,j)(�,�) (1≤i<j≤n1≤�<�≤�) where the sum of ai+aj��+�� is greater than or equal to l� and less than or equal to r� (that is, l≤ai+aj≤r�≤��+��≤�).

For example, if n=3�=3, a=[5,1,2]�=[5,1,2], l=4�=4 and r=7�=7, then two pairs are suitable:

  • i=1�=1 and j=2�=2 (4≤5+1≤74≤5+1≤7);
  • i=1�=1 and j=3�=3 (4≤5+2≤74≤5+2≤7).

Input

The first line contains an integer t� (1≤t≤1041≤�≤104). Then t� test cases follow.

The first line of each test case contains three integers n,l,r�,�,� (1≤n≤2⋅1051≤�≤2⋅105, 1≤l≤r≤1091≤�≤�≤109) --- the length of the array and the limits on the sum in the pair.

The second line contains n� integers a1,a2,...,an�1,�2,...,�� (1≤ai≤1091≤��≤109).

It is guaranteed that the sum of n� 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�<�), such that l≤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

解题说明:此题是一道数学题,为了找到这样数字组合,可以先对数列进行排序,排序后,用lower_bound和upper_bound找到边界,然后中间的就都是满足条件的数字对。

lower_bound返回第一个大于等于val的元素的迭代器

upper_bound返回第一个大于val的元素的迭代器

cpp 复制代码
#include<bits/stdc++.h>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		long long int n, l, r, k = 0;
		cin >> n >> l >> r;
		int a[200001];
		for (int i = 0; i < n; i++)
		{
			cin >> a[i];
		}
		sort(a, a + n);
		for (int i = 0; i < n; i++)
		{
			int j = lower_bound(a + i + 1, a + n, l - a[i]) - a;
			int p = upper_bound(a + i + 1, a + n, r - a[i]) - a;
			k = k + p - j;
		}
		cout << k << endl;
	}
	return 0;
}
相关推荐
2301_7951672021 小时前
Python 高手编程系列一十三:现实例子 — 延迟求值属性
开发语言·windows·python
报错小能手21 小时前
数据结构 不带头结点的双向循环链表
数据结构·算法·链表
Zfox_21 小时前
【Go】结构体、自定义类型与接口
开发语言·后端·golang
枫叶丹421 小时前
【Qt开发】Qt窗口(四) -> QDockWidget浮动窗口
c语言·开发语言·c++·qt·开源
星释21 小时前
Rust 练习册 101:字符串序列切片的艺术
开发语言·后端·rust
李玮豪Jimmy1 天前
Day26:贪心算法part4(452.用最少数量的箭引爆气球、435.无重叠区间、763.划分字母区间)
算法·贪心算法
秋深枫叶红1 天前
嵌入式第二十五篇——数据结构单向链表
c语言·数据结构·学习·算法
乌萨奇也要立志学C++1 天前
【洛谷】二分答案专题 3 道洛谷经典题(木材 / 砍树 / 跳石头)精讲
c++·算法
6***83051 天前
VMware虚拟机配置桥接网络
开发语言·网络·php
de_furina1 天前
[C++]string类的使用和模拟实现
开发语言·c++·gitee