题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4334
题目大意:求每行任取一个数,问5个数加起来和能否等于0
算法:哈希 邻接表
思路:把前两行每两个数字的和取余 放入邻接表中,然后判断后面三个数字的和的相反数是否在此邻接表中~~
#include<cstdio>
#include<cstring>
using namespace std;
#define LL __int64
struct HH
{
int next;
LL w;
}edge[50000];
const int Max = 1000007;
LL val[5][205];
int head[Max+1];
int tot ;
void add_edge(LL s)
{
int p = (s % Max + Max) % Max;
edge[tot].w = s;
edge[tot].next = head[p];
head[p] = tot ++;
}
int find( LL sum)
{
int i;
int p = (sum % Max + Max) % Max;
for(i = head[p]; i != -1; i = edge[i].next)
if(sum == edge[i].w )
return 1;
return 0;
}
int main()
{
int T, n, m;
scanf("%d", &T);
while(T --)
{
tot = 0;
int i, j, k;
int flag = 0;
memset(head, -1, sizeof(head));
scanf("%d", &n);
LL sum = 0;
for(i = 0; i < 5; i ++)
for(j = 1; j <= n; j ++)
scanf("%I64d", &val[i][j]);
for(i = 1; i <= n; i ++)
for(j = 1; j <= n; j ++)
{
sum = val[0][i] + val[1][j];
add_edge(sum);
}
for(i = 1; i <= n && !flag; i ++)
for(j = 1; j <= n && !flag; j ++)
for(k = 1; k <= n && !flag; k ++)
{
sum = val[2][i] + val[3][j] + val[4][k];
sum *= -1;
if(find(sum))
flag = 1;
}
if(flag == 1)
printf("Yes\n");
else
printf("No\n");
}
return 0;
}