HDU 2141Can you find it(二分查找)

来源:互联网 发布:23周b超数据 编辑:程序博客网 时间:2024/05/19 16:49

Can you find it?

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


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 31 2 31 2 31 2 331410
 

Sample Output
Case 1:NOYESNO
 



#include<iostream>
#include<stdio.h>
#include<algorithm>
using namespace std;
const int maxn=505;
int a[maxn],b[maxn],c[maxn];
int ab[maxn*maxn];
int L,N,M,S,X;
int main()
{
bool bs(int [],int,int,int);
int i,j;
int to_find;//to_find=S-a[i]-b[j],然后再c数组中找是否存在此数
int num=0;//用来记录当前为第几组数据
while(scanf("%d%d%d",&L,&N,&M)!=EOF)
{
num++;
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]);}
scanf("%d",&S);
int len=L*N;
int k=0;
/*要把a的每一项和b的每一项的和值存到数组ab中,
防止以后反复计算a和b数组中的某两项的和,
由此会造成三重循环超时,这三重循环为这两重循环嵌套while(S--)*/
for(i=0;i<L;i++)
for(j=0;j<N;j++)
{
ab[k++]=a[i]+b[j];
}
sort(ab,ab+len);
sort(c,c+M);
printf("Case %d:\n",num);
while(S--)
{
scanf("%d",&X);
/*以c数组为基础,在数组ab中用二分查找X-c[i]*/
for(i=0;i<M;i++)
{
if(bs(ab,0,len-1,X-c[i]))
{printf("YES\n");break;}
}
if(i==M){printf("NO\n");}
}
}
return 0;
}
bool bs(int array[],int begin,int end,int key)

while(begin<end)
{  
int mid=begin+(end-begin)/2;
if(array[mid]==key){return true;}
else if(array[begin]==key){return true;}//
else if(array[end]==key){return true;}//
else if(array[mid]>key){end=mid;}
else{begin=mid+1;}
}
return false;
}

0 0
原创粉丝点击