题解:CF1538C Number of Pairs

· · 题解

CF1538C Number of Pairs 题解

题目传送门

描述

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

思路

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

#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;
}

:::: ::::success[code 2]

#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;
} 

::::