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
思想很暴力,纯暴力的方法为n的5次方,显然不能过。用hash进行离散优化(比赛的时候写的二分果断TLE)
hash的复杂度是n的3次方,而二分的复杂度是n的三次方乘以15左右。
将第一行加上第二行的值的相反数起来存入hash表中,然后查询第三行加第四行加第五行的值是否在 hash表中出现,如果出现则为yes,否则为no
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<vector>
using namespace std;
const int maxn=210;
const int MOD=1000007;//hash离散化,模上一个数字
struct in
{
__int64 val;//保存当前的值
int next;//因为存在负数,也就是同一个tmp保存了两个值
}hash[maxn*maxn];
__int64 org[6][maxn];
int head[MOD];
int N,n;
int tot;
void init()
{
tot=0;
memset(head,-1,sizeof(head));
}
void add_hash(__int64 val)
{
int tmp=val%MOD;
tmp=tmp>=0?tmp:-tmp;
for(int i=head[tmp];i!=-1;i=hash[i].next)//i判定读入的值之前是否有读入,head[tmp]保存出现值的位置
// i最多为两个值,tmp为正数时的位置和 tmp为负数时的位置
{
if(hash[i].val==val)
return;
}
hash[tot].val=val;
hash[tot].next=head[tmp];
head[tmp]=tot++;//有新值读入才++
}
bool query(__int64 val)
{
int tmp=val%MOD;
tmp=tmp>=0?tmp:-tmp;
for(int i=head[tmp];i!=-1;i=hash[i].next)
{
if(hash[i].val==val)
return true;
}
return false;
}
bool slove()
{
int i,j,k;
for( i=0;i<n;i++)
{
for( j=0;j<n;j++)
{
for( k=0;k<n;k++)
{
if(query((org[2][i]+org[3][j]+org[4][k])))
return true;
}
}
}
return false;
}
int main()
{
scanf("%d",&N);
while(N--)
{
scanf("%d",&n);
init();
for(int i=0;i<5;i++)
{
for(int j=0;j<n;j++)
scanf("%I64d",&org[i][j]);
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
add_hash(-(org[0][i]+org[1][j]));
}
if(slove())
{
puts("Yes");
}
else
{
puts("No");
}
}
return 0;
}