HDU 2141 Can you find it?(二分)

上题:
Give you three sequences of numbers A, B, C, then we give you a number X. Now you need to calculate if you can find the three numbers Ai, Bj, Ck, which satisfy the formula Ai+Bj+Ck = X.
Input
There are many cases. Every data case is described as followed: In the first line there are three integers L, N, M, in the second line there are L integers represent the sequence A, in the third line there are N integers represent the sequences B, in the forth line there are M integers represent the sequence C. In the fifth line there is an integer S represents there are S integers X to be calculated. 1<=L, N, M<=500, 1<=S<=1000. all the integers are 32-integers.
Output
For each case, firstly you have to print the case number as the form "Case d:", then for the S queries, you calculate if the formula can be satisfied or not. If satisfied, you print "YES", otherwise print "NO".
Sample Input
3 3 3
1 2 3
1 2 3
1 2 3
3
1
4
10
Sample Output
Case 1:
NO
YES
NO
大致题意:就是给你三个数列,A,B,C 从这三个数列中选取三个数,Ai,Bi,Ci 输入一个数X 使得 Ai+Bi+Ci=X,如果找得到就输出YES,找不到就输出NO,
思路:
起初看到之后 直接三层for循环,果断超时,之后又试了一发大表,交过才发现 “all the integers are 32-integers.”所以开始写二分,最初的二分将a和b的和算出来存到sum数组中,之后从c中二分找到X-sum[i],之后还是交了一发超时。。。二分都超时,心态爆炸了。。之后仔细想了一下,我如果枚举sum数组的话那么枚举的长度最大会是500*500,这么大不超时才怪好吗,那我如果枚举c数组,然后利用二分在sum里面找那就长度就可以大大减少了,于是就这样过了
上代码
#include<stdio.h>
#include<algorithm>
using namespace std;
int a[510],b[510],c[510];
int sum[2555555];
int check(int len,int target)
{
	int head=0,tail=len-1;
	while(tail>head)
	{
		//printf("---\n");
		int mid=(head+tail)/2;
		if(sum[mid]>target)
		{
			tail=mid;
		}
		else if(sum[mid]<target)
		{
			head=mid+1;
		}
		else if(sum[mid]==target)
		{
			return 1;
		}
	}
	return 0;
}
int main()
{
	int l,n,m;
	int ca=0;
	while(scanf("%d%d%d",&l,&n,&m)!=EOF)
	{
		int len=0;
		for(int i=0;i<l;i++) scanf("%d",&a[i]);
		for(int i=0;i<n;i++) scanf("%d",&b[i]);
		for(int i=0;i<m;i++) scanf("%d",&c[i]);
		for(int i=0;i<l;i++)
		{
			for(int j=0;j<n;j++)
			{
				sum[len++]=a[i]+b[j];
			}
		}
		sort(sum,sum+len);
		sort(c,c+m);
		int s;
		int t;
		int flag;
		scanf("%d",&s);
		printf("Case %d:\n",++ca);
		while(s--)
		{
			flag=0;
			int fa;
			scanf("%d",&fa);
			for(int i=0;i<l;i++)
			{
				t=check(len,fa-c[i]);
				if(t==1)
				{
					flag=1;
					printf("YES\n");
					break;
				}
			}
			if(!flag)
			{
				printf("NO\n");
			}
			
		}
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值