hdu 4334 Trouble

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

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值