HDU-2141 Can you find it? 二分查找(详细思路)

本文介绍了一种解决三数组求和匹配问题的算法。通过将前两个数组的所有可能组合进行排序,然后使用二分查找法来判断第三个数组中的元素是否能够与前两个数组的组合相加得到指定的目标值。这种方法避免了穷举搜索,大大提高了效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

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,每个数组取一个数,判断是否能加出来下面的数

【思路】:二分查找,因为给了三个数组,如果把三个数组能组合出来的所有情况都遍历出来存到一个数组里面,这个数组需要开500*500*500,显然开不了这么大的。于是就把前两个数组的所有能组合出来的数都存到一个数组里,再把这个数组sort一下。因为a+b+c=x,所以a+b=x-c。所有a+b已经有了,遍历x-c[i],用二分查找寻找有没有a+b=x-c。就酱~

二分查找就是那个find函数

AC代码

#include <stdio.h>
#include <algorithm>
using namespace std;
int y,ab[300000];
int find(int l,int r){
	int mid=(l+r)/2;
	if(ab[mid]==y) return 1;
	if(l==r) return -1;
	if(ab[mid]<y) find(mid+1,r);
	else find(1,mid);
}
int main(){
	int i,j,l,n,m,a[500],b[500],c[500],cnt=1;
	while(~scanf("%d%d%d",&l,&n,&m)){
		for(i=0;i<l;i++)
			scanf("%d",&a[i]);
		for(i=0;i<n;i++)
			scanf("%d",&b[i]);
		for(i=0;i<m;i++)
			scanf("%d",&c[i]);
		int len=0;
		for(i=0;i<l;i++)
			for(j=0;j<n;j++)
				ab[len++]=a[i]+b[j];
		sort(ab,ab+len);
		int s,x;
		scanf("%d",&s);
		printf("Case %d:\n",cnt++);
		while(s--){
			scanf("%d",&x);
			int flag=0;
			for(i=0;i<m&&flag!=1;i++){
				y=x-c[i];
				flag=find(1,len);
			}
			if(flag==1) printf("YES\n");
			else printf("NO\n");
		}
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值