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是否等于给定的数值X
Ai+Bj+Ck=X;
暴力枚举会炸,可以先处理前两个数字的和O(n^2),排序,之后枚举X-Ck,二分找
二分查找
步骤1、设置数组s[n]来存放n个已排好序的元素;变量low和high表示查找范围在数组中的上界和下界;middle表示查找范围的中间位置,x为特定元素
步骤2、初始化,low=0,即指向s中的第一个元素;high=n-1,即指向s中的最后一个元素
步骤3:、middle=(low+high)/2,即指向查找范围的中间元素
步骤4、判定low<=high是否成立,如果成立,转步骤5,否则,算法结束
步骤5、判断x与s[middle] 的关系,如果等于s[middle],算法结束,如果大于s[middle],则令low=middle+1;否则令high=middle-1,转步骤3
代码实现
//非递归方式
int dd(int a[],int n,int x){//x表示要查找的元素
int low=0,high=n-1;
int mid;
while(low<=high){
mid=(low+high)/2;
if(a[mid]>x){
high=mid-1;
}
else if(a[mid]<x){
low=mid+1;
}
else return mid;
}
return -1;
}
//递归方式
int dd(int s[],int x,int low,int high){
if(low>high)
return -1;
int mid=(low+high)/2;
if(x==s[mid])
return mid;
else if(x>s[mid])
return dd(s,x,mid+1,high);
else
return dd(s,x,low,mid-1);
}
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
/****二分法 暴力枚举(三个for)会超时
计算每个数组找一个数之和是否能够等于给定 的数值****/
int l[505],n[505],m[505];
int a[250005];//l与n的组合
int dd(int low,int high,int x){
int mid;
while(low<=high){
mid=(low+high)/2;
if(a[mid]>x){
high=mid-1;
}
else if(a[mid]<x){
low=mid+1;
}
else return 1;
}
return -1;
}
int main(){
int L,N,M;
int len,t;
int S;
int num=0;
int x,k;
while(scanf("%d%d%d",&L,&N,&M)>0){
for(int i=1;i<=L;i++){
scanf("%d",&l[i]);
}
for(int i=1;i<=N;i++){
scanf("%d",&n[i]);
}
for(int i=1;i<=M;i++){
scanf("%d",&m[i]);
}
len=L*N;
t=0;
for(int i=1;i<=L;i++){
for(int j=1;j<=N;j++){
a[++t]=l[i]+n[j];
}
}
//排序
sort(a+1,a+1+len);
scanf("%d",&S);
printf("Case %d:\n",++num);
while(S--){
scanf("%d",&x);
for(int i=1;i<=M;i++)
{
k=dd(1,len,x-m[i]);
if( k==1 ) break;
}
if( k==-1) printf("NO\n");
else printf("YES\n");
}
}
return 0;
}