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
这题只要注意时间的复杂度就好,先把后两个相加然后二分,枚举第一个
#include <iostream>
#include<cstdio>
#include"algorithm"
#include<cstring>
using namespace std;
#define num 501
static int L[num],M[num],N[num],Mix[num*num];//,S[1005];
int binary(int a,int*arr,int high);
int main()
{
int a,b,c,n,temp,s;
int Count=1;
while(cin>>a>>b>>c){
for(int i=0;i<a;i++) cin>>L[i];
for(int i=0;i<b;i++) cin>>M[i];
for(int i=0;i<c;i++) cin>>N[i];
/*先计算后两组数的和,去重,二分第一个*/
int Max=0;
for(int i=0;i<b;i++){
for(int j=0;j<c;j++){
if(Mix[Max]!=M[i]+N[j]) Mix[Max++]=M[i]+N[j];
}
}
sort(Mix,Mix+Max);
cin>>n;
// for(int i=0;i<n;i++) cin>>S[i];
/*对第一组数进行二分查找*/
cout<<"Case "<<Count<<":"<<endl;
for(int i=0;i<n;i++){
cin>>s;
temp=0;
// cout<<"test"<<endl;
for(int j=0;j<a;j++){
temp=binary(s-L[j],Mix,Max);
if(temp==1) break;
}
if(temp==1) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
/*重置操作*/
Count++;
memset(L,0,sizeof(L));
memset(M,0,sizeof(M));
memset(N,0,sizeof(N));
// memset(S,0,sizeof(S));
memset(Mix,0,sizeof(Mix));
}
return 0;
}
/*二分函数*/
int binary(int a,int*arr,int high){
int mid;
int low=0;
// int high=num;
while(low<=high){
mid=((high-low)>>1)+low;
if(arr[mid]==a) return 1;
else if(arr[mid]<a) low=mid+1;
else high=mid-1;
}
return -1;
}