Trouble
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 3773 Accepted Submission(s): 1182
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?
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
Source
Recommend
zhoujiaqi2010
题意:
有5个数组,都含有N个数。从每个数组里选一个数相加,如果等于0,输出Yes,反之输出No.
分析:
如果用5个for循环或者深搜都是TLE的节奏。怎么缩小复杂度呢?
转化为3SUM问题,将第一堆和第二堆合并,第三堆和第四堆合并,复杂度O(N^2*log(N^2))。
枚举第五堆,查找一个的复杂度是O(N^2),总复杂度O(N^3)。
代码:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#define N 210
#define ll long long
using namespace std;
ll list1[N*N];
ll list2[N*N];
ll list3[N];
ll dig[6][N];
int main()
{
int i,j,k,cnt,t,n,l1,l2,l3;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(i=0;i<5;i++)
{
for(j=0;j<n;j++)
scanf("%I64d",&dig[i][j]);
}
cnt=0;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
list1[cnt++]=dig[0][i]+dig[1][j];
}
l1=cnt;
cnt=0;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
list2[cnt++]=dig[2][i]+dig[3][j];
}
l2=cnt;
cnt=0;
for(i=0;i<n;i++)
list3[cnt++]=dig[4][i];
l3=cnt;
sort(list1,list1+l1);
sort(list2,list2+l2);
sort(list3,list3+l3);
bool have=0;
for(i=0;i<l3&&have==0;i++)
{
j=0,k=l2-1;
while(j<l1&&k>=0)
{
if(list1[j]+list2[k]==-list3[i])
{
have=true;
break;
}
else if(list1[j]+list2[k]>-list3[i])
k--;
else j++;
}
}
if(have) puts("Yes");
else puts("No");
}
return 0;
}