#include<iostream> #include<cstring> #include<cstdio> #include<algorithm> using namespace std; const int MM=1000100; long long a[5][205]; long long hash[MM]; bool counter[MM]; int hash_find(long long num){ int t; t=num%MM; if(t<0) t+=MM; while(counter[t] && hash[t]!=num) t=(t+1)%MM; return t; } int main(){ int t,Case=0,n; scanf("%d",&t); while(t--){ scanf("%d",&n); for(int i=0;i<5;i++){ for(int j=0;j<n;j++) scanf("%I64d",&a[i][j]); } memset(counter,0,sizeof(counter)); long long num,pos; for(int i=0;i<n;i++) for(int j=0;j<n;j++){ num=-(a[0][i]+a[1][j]); pos=hash_find(num); hash[pos]=num; cout<<"hash["<<pos<<"]: "<<num<<endl; counter[pos]=true; } int flag=0; for(int i=0;i<n;i++) for(int j=0;j<n;j++) for(int k=0;k<n;k++){ num=a[2][i]+a[3][j]+a[4][k]; pos=hash_find(num); cout<<"---hash["<<pos<<"]: "<<num<<endl; if(counter[pos]){ flag=1; i=j=n; break; } } if(flag) puts("Yes"); else puts("No"); } return 0; }
用前两行和的相反数的所有情况建立哈希表。后三行的和查表,存在相等的就yes了!
Trouble
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2628 Accepted Submission(s): 813
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