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
 

解题思路:

  首先我们考虑这个问题:给定两个序列A,B,和确定的数x,问是否存在i,j使满足A[i]+B[j]=x的?最快的方法是枚举A,然后在B中二分查找

x-A。现在回到这个问题,这道题给了三组序列A,B,C如何查找呢?我们不妨将A,C两数组合并成新数组LN,LN中每个元素都是Ai+Bj的和。然后枚举B,在LN中二分查找x-B。

*这里有个细节:由于x为32位整数,当A+B>INT32_MAX时,可以不用加入LN.

代码如下:

 #include <iostream>
#include <cstdio>
#include <algorithm>
#include <time.h>
using namespace std;
#define clock__ printf("%f\n",double(clock())/CLOCKS_PER_SEC);
#define maxn 500
#define INT_32_MAX ((1<<31)-1)
typedef long long LL;
int A[maxn+],B[maxn+],C[maxn+];
int L,M,N,S;
int LN[maxn*maxn+];
int h; bool search_LN(int a,int b,int x){
int len=b-a;
int mid=a+len/;
if(len==){
if(LN[a]==x) return true;
else return false;
}
if(LN[mid]==x) return true;
else if(LN[mid]>x) return search_LN(a, mid, x);
else return search_LN(mid, b, x);
} int main() { int T=;
while(scanf("%d%d%d",&L,&M,&N)==){
printf("Case %d:\n",++T);
for(int i=;i<L;i++)
scanf("%d",&A[i]);
for(int i=;i<M;i++)
scanf("%d",&B[i]);
for(int i=;i<N;i++)
scanf("%d",&C[i]);
h=;
for(int i=;i<L;i++)
for(int j=;j<N;j++){
if(LL(A[i])+C[j]<=INT_32_MAX)
LN[h++]=A[i]+C[j];
}
sort(LN, LN+h);
scanf("%d",&S);
for(int i=;i<=S;i++){
int x;
scanf("%d",&x);
bool ok=;
for(int j=;!ok&&j<M;j++){
if(search_LN(,h, x-B[j]))
ok=;
}
if(ok)printf("YES\n");
else printf("NO\n");
}
}
//clock__
return ;
}
05-22 06:58