Trouble

Problem Description

Hassan is in trouble. His mathematics teacher has given him a very difficult problem called 5-sum. Please help him. The 5-sum problem is defined as follows: Given 5 sets S_1,...,S_5 of n integer numbers each, is there a_1 in S_1,...,a_5 in S_5 such that a_1+...+a_5=0?

Input

First line of input contains a single integer N (1≤N≤50). N test-cases follow. First line of each test-case contains a single integer n (1<=n<=200). 5 lines follow each containing n integer numbers in range [-10^15, 1 0^15]. I-th line denotes set S_i for 1<=i<=5.

Output

For each test-case output "Yes" (without quotes) if there are a_1 in S_1,...,a_5 in S_5 such that a_1+...+a_5=0, otherwise output "No".

Sample Input

2
2
1 -1
1 -1
1 -1
1 -1
1 -1
3
1 2 3
-1 -2 -3
4 5 6
-1 3 2
-4 -10 -1

Sample Output

No
Yes
题意:给定5行数每行取一个组合值为0
思路:用前两行组合数的负值建立hash表后面三行查询
#include<stdio.h>
#include<string.h>
#include<iostream>
#define ll __int64
#define MM 1000100
ll p[5][210];
ll  hash[MM];
bool visit[MM];
ll find(ll num)
{
    ll t;
    t=num%MM;
    if(t<0) t+=MM;
    while(visit[t]==1&&hash[t]!=num)  t=(t+1)%MM;
    return t;
}
int main()
{
    ll ca,i,j,x,t,pos,flag,k;
    ll n;
    scanf("%I64d",&ca);
    while(ca--)
    {
        scanf("%I64d",&n);
        flag=0;
        for(i=0;i<5;i++)
        {
            for(j=0;j<n;j++)
            {
                scanf("%I64d",&p[i][j]);
            }
        }
        memset(visit,0,sizeof(visit));
        //memset(hash,0,sizeof(hash));
        for(i=0;i<n;i++)
        {
            for(j=0;j<n;j++)
            {
                x=-(p[0][i]+p[1][j]);
                t=find(x);
                visit[t]=1;
                hash[t]=x;
            }
        }
        for(i=0;i<n;i++)
        {
            for(j=0;j<n;j++)
            {
                for(k=0;k<n;k++)
                {
                    x=(p[2][i]+p[3][j]+p[4][k]);
                    pos=find(x);
                    if(visit[pos]==1){flag=1;i=n;j=n;break;}
                }
            }
        }
        if(flag) puts("Yes");
        else puts("No");
    }
    return 0;
}
posted @ 2013-05-19 11:14  forevermemory  阅读(220)  评论(0编辑  收藏  举报