Can you find it? (HDU_2141) 二分查找

Can you find it?

Time Limit: 10000/3000 MS (Java/Others)    Memory Limit: 32768/10000 K (Java/Others)
Total Submission(s): 21724    Accepted Submission(s): 5499


Problem Description
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
 

Author
wangye



题意:给出三个数字序列A,B,C,及X,求问是否存在Ai + Bj + Ck = X

解题思路:二分查找。

代码如下:

#include"iostream"
#include"cstring"
#include"cstdio"
#include"algorithm"
using namespace std; 

int a[505], b[505];
int bc[505*505];

int Binary_Search(long long x,int n){
	int low = 0, high = n, mid = 0, flag = 0;
	while(low <= high && flag == 0){
		mid = (low + high)>>1;
		if(bc[mid] == x) flag = 1;
		else if(x < bc[mid]) high = mid - 1;
		else low = mid + 1;
	}
	return flag;
}

int main(){
	int l, n, m, s, f ,cas = 0;
	int t;
	while(scanf("%d%d%d",&l,&n,&m) != EOF){
		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",&t);
			for(int j = 0;j < n;j ++)
				bc[i*n + j] = b[j] + t; 
		}
		sort(bc,bc+n*m-1);
		printf("Case %d:\n",++cas);
		scanf("%d",&s);
		while(s --){
			f = 0;
			scanf("%d",&t);
			for(int i = 0;i < l;i ++)
				if (Binary_Search(t-a[i],n*m-1)){
					f = 1;
					break;
				}
			if(f) printf("YES\n");
			else printf("NO\n");
		}
	}
	return 0;
}




你可能感兴趣的:(二分查找)