P1102 A-B 数对

P1102 A-B 数对

 

思路: 枚举B,对于每个B检查B+C(即)A的个数,将这个数直接加到答案上.

于是想到开个桶,但是数据是32位带符号整数范围.即使是int也只能开到107.

直接看答案吧.

#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;

int n, c;
long long s[200010], ans;

int main(){
    cin >> n >> c;
    for(int i = 0; i < n; i++)
        cin >> s[i];
    sort(s, s + n);    // s调整为升序排列

    for(int i = 0; i < n; i++)
        ans += (upper_bound(s, s + n, s[i] + c) - s) - (lower_bound(s, s + n, s[i] + c) - s);

    cout << ans << endl;

    return 0;
}

upper_bound返回满足s[x]>=s[i]+c的最小位置(指针),lower_bound返回满足s[x]>s[i]+c的最小位置.他们的复杂度是O(nlogn).

这两个位置的差就是"A的个数".

原文地址:https://www.cnblogs.com/Gaomez/p/14125993.html