POJ 2785 4 Values whose Sum is 0 (二分)题解

思路:

如果用朴素的方法算O(n^4)超时,这里用折半二分。把数组分成两块,分别计算前后两个的和,然后枚举第一个再二分查找第二个中是否有满足和为0的数。

注意和有重复

#include<iostream>
#include<algorithm>
#include<cstring>
#define ll long long
using namespace std;
const int N = 4000+5;
int a[N],b[N],c[N],d[N];
int mp1[N*N],mp2[N*N],cn1,cn2;
int main(){
    int n;
    scanf("%d",&n);
    for(int i = 1;i <= n;i++) scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]);
    cn1 = cn2 = 0;
    for(int i = 1;i <= n;i++){
        for(int j = 1;j <= n;j++){
            mp1[cn1++] = a[i] + b[j];
            mp2[cn2++] = c[i] + d[j];
        }
    }
    sort(mp2,mp2+cn2);
    ll ans = 0;
    for(int i = 0;i < cn1;i++){
        int x = lower_bound(mp2,mp2+cn2,-mp1[i]) - mp2;
        if(mp1[i] + mp2[x] == 0) ans += upper_bound(mp2,mp2+cn2,-mp1[i]) - mp2 - x;
    }
    printf("%lld\n",ans);
    return 0;
}


posted @ 2018-07-06 11:39  KirinSB  阅读(106)  评论(0编辑  收藏  举报