HDU - 4334 Trouble

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?InputFirst 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.OutputFor 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
我是将钱两个和哈希,再计算后三个和哈希匹配。
 1 #include <cstdio>
 2 #include <iostream>
 3 #include <cstring>
 4 #include <algorithm>
 5 using namespace std;
 6 
 7 const int mod=401704; 
 8 long long  a[5][210],Hash[mod];
 9 bool color[mod];
10 
11 int judge(long long x)
12 {
13     int s=x%mod;
14     if(s<0) s+=mod;
15     while(color[s]&&Hash[s]!=x)
16         s=(s+1)%mod;
17     return s;
18 }
19 
20 int main()
21 {
22     int  T, n;
23     cin >> T;
24     while(T--)
25     {
26         scanf("%d",&n);
27         memset(color,0,sizeof(color));
28         for(int i=0; i<5; i++)
29             for(int j=0; j<n; j++)
30                scanf("%lld",&a[i][j]);
31         for(int i=0; i<n; i++)
32             for(int j=0; j<n; j++)
33             {
34                 long long sum=-(a[0][i]+a[1][j]);
35                 int h=judge(sum);
36                 color[h]=1;
37                 Hash[h]=sum;
38             }
39         bool ok=false;
40         for(int i=0; i<n&&!ok; i++)
41            for(int j=0; j<n&&!ok; j++)
42               for(int k=0; k<n&&!ok; k++)
43               {
44                   long long sum=a[2][i]+a[3][j]+a[4][k];
45                   int h=judge(sum);
46                   if(color[h])
47                   {
48                       ok=true; break;
49                   }
50               }
51         if(ok) printf("Yes\n");
52         else printf("No\n");
53     }
54     return 0;
55 }

 

posted @ 2017-08-08 18:26  西北会法语  阅读(130)  评论(0编辑  收藏  举报