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?
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 给你5个数组每个都有N个元素,然后在每一个数组里面取一个数看能否为0
这题5个for不用想肯定TEL 分治的思想 将第一个数组和第二个数组合并 第三个和第四个合并
这样就只有3个数组了。
下面的上代码 ,细节在代码里面体现
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
long long cnt[][];
long long a[],b[],c[]; int main() {
int t;
scanf("%d",&t);
while(t--){
int n;
scanf("%d",&n);
for (int i= ;i< ;i++ ){
for (int j= ;j<n ;j++){
scanf("%lld",&cnt[i][j]);
}
}
int k=;
for (int i= ;i<n ;i++ ){
for (int j= ;j<n ;j++ ){
a[k]=cnt[][i]+cnt[][j];
k++;
}
}
k=;
for (int i= ;i<n ;i++ ){
for (int j= ;j<n ;j++ ){
b[k]=cnt[][i]+cnt[][j];
k++;
}
}
int len=;
for (int i= ;i<n ;i++){
c[len++]=cnt[][i];
}
sort(a,a+k);
sort(b,b+k);
sort(c,c+len);
int flag=,temp1,temp2;
for (int i= ;i<n ;i++){
temp1=k-;
temp2=;
while(temp1>= &&temp2<k) {
if (a[temp1]+b[temp2]+c[i]==) {
flag=;
break;
}else if (a[temp1]+b[temp2]+c[i]>) {
temp1--;
}else temp2++;
}
if (flag==) break;
}
if (flag==) printf("Yes\n");
else printf("No\n");
}
return ;
}