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;
}