Number of Pairs[二分查找函数]

Number of Pairs

题面翻译

【题目描述】

给出一个由整数组成的数组 a a a,求一对整数 ( i , j ) (i, j) (i,j) 1 ≤ i < j ≤ n 1 \le i < j \le n 1i<jn)满足 l ≤ a i + a j ≤ r l \le a_i + a_j \le r lai+ajr 的数量。

【输入格式】

在输入的第一行为一个整数 t t t 1 ≤ t ≤ 10 4 1 \le t \le {10}^4 1t104),为数据组数。

接下来对于每组数据,第一行为三个整数 n , l , r n,l,r n,l,r 1 ≤ n ≤ 2 × 10 5 1 \le n \le 2 \times {10}^5 1n2×105 1 ≤ l ≤ r ≤ 10 9 1 \le l \le r \le {10}^9 1lr109),为数组的长度和上文中的 l , r l, r l,r。第二行有 n n n 个整数 a 1 , a 2 , … , a n a_1, a_2, \ldots , a_n a1,a2,,an 1 ≤ a i ≤ 10 9 1 \le a_i \le {10}^9 1ai109)表示数组 a a a

保证对于所有组数据 ∑ n ≤ 2 × 10 5 \sum n \le 2 \times {10}^5 n2×105

【输出格式】

对于每组数据,输出满足条件的 ( i , j ) (i,j) (i,j) 组数。

题目描述

You are given an array $ a $ of $ n $ integers. Find the number of pairs $ (i, j) $ ( $ 1 \le i < j \le n $ ) where the sum of $ a_i + a_j $ is greater than or equal to $ l $ and less than or equal to $ r $ (that is, $ l \le a_i + a_j \le r $ ).

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

  • $ i=1 $ and $ j=2 $ ( $ 4 \le 5 + 1 \le 7 $ );
  • $ i=1 $ and $ j=3 $ ( $ 4 \le 5 + 2 \le 7 $ ).

输入格式

The first line contains an integer $ t $ ( $ 1 \le t \le 10^4 $ ). Then $ t $ test cases follow.

The first line of each test case contains three integers $ n, l, r $ ( $ 1 \le n \le 2 \cdot 10^5 $ , $ 1 \le l \le r \le 10^9 $ ) — the length of the array and the limits on the sum in the pair.

The second line contains $ n $ integers $ a_1, a_2, \ldots, a_n $ ( $ 1 \le a_i \le 10^9 $ ).

It is guaranteed that the sum of $ n $ overall test cases does not exceed $ 2 \cdot 10^5 $ .

输出格式

For each test case, output a single integer — the number of index pairs $ (i, j) $ ( $ i < j $ ), such that $ l \le a_i + a_j \le r $ .

样例 #1

样例输入 #1

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

样例输出 #1

2
7
0
1

思路分析:
从前面往后面扫一遍,每次都已当前位置为左边界,然后二分查找允许的边界,边界之差就是以当前点为左边界的所有情况符合条件的合集

函数介绍:

lower_bound://找到大于等于某一个数x的第一个数
upper_bound://找到大于某一个数x的第一个数
lower_bound(w+1+i,w+2+n,a-w[i]) - w;
//起始位置,终点位置,大于等于的数x,-w是为了明确返回坐标
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
using namespace std;
int t, l, r,n,a,b;
int w[200005];
int main()
{
    cin >> t;
    while (t--)
    {
        int num = 0;
        cin >> n >> a >> b;
        for (int i = 1; i <= n; i++) cin >> w[i];
        sort(w + 1, w + 1 + n);//排个序
        w[n + 1] = 1e9;//最为结束的标志
        for (int i = 1; i <= n; i++)
        {
            l = lower_bound(w+1+i,w+2+n,a-w[i]) - w;
            //从二号位开始找别忘了,我们是为了找最小右边界
            r = upper_bound(w+1+i,w+2+n,b-w[i]) - w;
            //从二号位开始找别忘了,我们是为了找最大右边界
            if (r > l) num += r - l;//答案数+++
        }
        cout << num << endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值