POJ 2785 4 Values whose Sum is 0

来源:互联网 发布:安卓编程权威指南第3版 编辑:程序博客网 时间:2024/06/06 01:17

you can find the problem here
the question let us to find 4 number from each row which sum fo them is zero. what we should do is to take two rows of tem as one row,get 2NN number, than us binary search to find compatible solution .

#include<iostream>#include <cstdio>#include<cstring>#include <algorithm>using namespace std;const int maxn = 4005;int a[maxn],b[maxn],c[maxn],d[maxn];int ab[maxn*maxn],cd[maxn*maxn];int main(){    int n = 0;    while(~ scanf("%d",&n))    {        for(int i=1; i<=n; i++) scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]);        int cnt = 0;        for(int i=1; i<=n; i++)        {            for(int j = 1; j<=n; j++)            {                ab[cnt] = a[i]+b[j];                cd[cnt++] = c[i]+d[j];            }        }        int ans = 0;        //sort(ab,ab+cnt);        sort(cd,cd+cnt);        for(int i=0; i<cnt; i++)        {            int s = ab[i];            //cout<<ab[i]<<endl;            if(binary_search(cd,cd+cnt,-s))            {                ans+=upper_bound(cd,cd+cnt,-s)-lower_bound(cd,cd+cnt,-s);            }        }        printf("%d\n",ans);    }    return 0;}