AtCoder Beginner Contest 077 C Snuke Festival(二分)

二分水题,A,B,C三个数组排序,对于每个B[i],二分算出来有多少A比他小,多少C比他大,然后扫一遍出结果。O(nlog(n))水过。

#include <bits/stdc++.h>
using namespace std;

const int MAXN = 1e5+10;
int A[MAXN],B[MAXN],C[MAXN];
int n;
//严格小于B[i]的数字个数  和 严格大于B[i]的数字个数
long long lnb[MAXN],unb[MAXN];

int main()
{
    ios::sync_with_stdio(false);
    cin >> n;
    for(int i = 0; i < n; ++i)
        cin >> A[i];
    sort(A,A+n);
    for(int i = 0; i < n; ++i)
        cin >> B[i];
    sort(B,B+n);
    for(int i = 0; i < n; ++i)
        cin >> C[i];
    sort(C,C+n);

    //对于每个b,先统计出来几个a比他小,O(nlog(n))
    for(int i = 0; i < n; ++i)
        lnb[i] = lower_bound(A,A+n,B[i]) - A;
    for(int i = 0; i < n; ++i)
        unb[i] = n - (upper_bound(C,C+n,B[i]) - C);
    long long res = 0;
    for(int i = 0; i < n; ++i)
        res += lnb[i]*unb[i];
    cout << res << endl;
    return 0;
}
原文地址:https://www.cnblogs.com/guoyongheng/p/7787173.html