T711542 数对查找

· · 个人记录

先读题:

给出一串正整数数列以及一个正整数 C,要求计算出所有满足 A−B=C 的数对的个数(不同位置的数字一样的数对算不同的数对)。

给定一个数组和一个数字C

求a[i] - a[j] == c

可以用二分实现

#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N = 2e5 + 10;
int n,a[N],m;
signed main(){
    cin>>n>>m;
    for(int i=1;i<=n;i++)cin>>a[i];
    sort(a + 1,a + 1 + n);
    int cnt = 0;
        for(int i=1;i<=n;i++){
            int x = a[i] -  m;
        int pos = lower_bound(a + 1,a + 1 + n,x)- a;
        int net = upper_bound(a + 1,a + 1 + n,x)- a - 1;
        if(pos != n + 1 && a[pos] == x){
            cnt += net - pos + 1;
        }
    }
    cout<<cnt;
    return 0;
}