1. 程式人生 > >POJ 2785 4 Values whose Sum is 0

POJ 2785 4 Values whose Sum is 0

http 代碼 ble tput limit earch log 多少 lsp

4 Values whose Sum is 0
Time Limit: 15000MS Memory Limit: 228000K
Total Submissions: 22691 Accepted: 6869
Case Time Limit: 5000MS

Description

The SUM problem can be formulated as follows: given four lists A, B, C, D of integer values, compute how many quadruplet (a, b, c, d ) ∈ A x B x C x D are such that a + b + c + d = 0 . In the following, we assume that all lists have the same size n .

Input

The first line of the input file contains the size of the lists n (this value can be as large as 4000). We then have n lines containing four integer values (with absolute value as large as 228 ) that belong respectively to A, B, C and D .

Output

For each input file, your program has to write the number quadruplets whose sum is zero.

Sample Input

6
-45 22 42 -16
-41 -27 56 30
-36 53 -37 77
-36 30 -75 -46
26 -38 -10 62
-32 -54 -6 45

Sample Output

5

Hint

Sample Explanation: Indeed, the sum of the five following quadruplets is zero: (-45, -27, 42, 30), (26, 30, -10, -46), (-32, 22, 56, -46),(-32, 30, -75, 77), (-32, -54, 56, 30).

Source

Southwestern Europe 2005 題目大意
:給出四列數A,B,C,D,每列中選出一個數啊a,b,c,d,問有多少種情況可以使得a+b+c+d=0。 大致思路:直接用四個循環超時是肯定的,這時可以用折半的方法,先求a[i]+b[i],再求c[i]+d[i],用二分找出c[i]+d[i]中滿足的情況。詳見代碼(本題還能用hash做)
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
using namespace std;
#define maxn 4005
int a[maxn],b[maxn],c[maxn],d[maxn];
int ab[maxn*maxn],cd[maxn*maxn];
int main()
{
    int i,j,N,lo,hi,mid,cou=0,p=0;
    cin>>N;
    for(i=0;i<N;i++)
        cin>>a[i]>>b[i]>>c[i]>>d[i];
    for(i=0;i<N;i++)
        for(j=0;j<N;j++)
        {
            ab[p]=a[i]+b[j];
            p++;
        }
        sort(ab,ab+N*N);
    p=0;
    for(i=0;i<N;i++)
        for(j=0;j<N;j++)
        {
            cd[p]=c[i]+d[j];
            p++;
        }
        sort(cd,cd+N*N);
    for(i=0;i<p;i++)
    {
        lo=0;hi=p;//從p-1和p開始二分都行
        while(lo<hi)//這個循環會找到一個與要找的數相等的最小下標
        {
            mid=(lo+hi)/2;
            if(ab[mid]<-cd[i])//因為是排好序的,所以可以直接利用數組下標二分
                lo=mid+1;
            else hi=mid;
        }
        while(ab[lo]==-cd[i]&&lo<p)//判斷lo和lo之後是否相等,因為可能會有數據相同,註意lo<p!!!
        {
            cou++;
            lo++;
        }
    }
    cout<<cou<<endl;
    return 0;
}

POJ 2785 4 Values whose Sum is 0