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
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
题目大意:输入五行数字,从每行拿一个数字加起来是否等于0,如果存在就输出yes,否则输出no;
解题思路:别人用的是hash,但是我对hash不太了解,所以就把五行缩成3行,然后排序查找。
AC代码:
#include<stdio.h>
#include<algorithm>
using namespace std;
long long data[5][205];
long long a1[40005],a2[40005];
int main()
{
int t,n,i,j,c,l1,l2,h,k;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(i=0;i<5;i++)
for(j=0;j<n;j++)
scanf("%I64d",&data[i][j]);//(这里long long输入一定要用I64,用lld是wa,让我纠结了好长时间)
c=0;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
a1[c++]=data[0][i]+data[1][j];
l1=c;
c=0;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
a2[c++]=data[2][i]+data[3][j];
l2=c;
h=0;
sort(a1,a1+l1);
sort(a2,a2+l2);
for(i=0;i<n;i++)
{
j=0;
k=l2-1;
while(j<l1&&k>=0)
{
if(a1[j]+a2[k]==-data[4][i])
{
h=1;
break;
}
if(a1[j]+a2[k]>-data[4][i])
k--;
if(a1[j]+a2[k]<-data[4][i])
j++;
}
if(h) break;
}
if(h) printf("Yes\n");
else printf("No\n");
}
return 0;
}