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.
InputThere 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.
OutputFor 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 10Sample Output
Case 1: NO YES NO
文章大概意思是:第一行L,M,N,第二行L个数,第三行M个数,第四行N个数,第五行一个S,表示接下来有S次询问Ai,是否能在L,M,N中各找一个数相加等于Ai。
这道题我看完第一个想法就是暴力解决,直接算出来L,M,N相加的所以结果,时间复杂度为O(n^3),然后用二分查找,我试了一下,结果超时了,空间超限。
第二种思想就是半暴力解决,算出L,M相加的结果SUM,然后用Ai减去,在N中查找,看是否能找到。(SUMk+Nj=Ai)时间复杂度为O(N^2+lgN),本来想着会WA,结果AC了,算是水过呀。。。。
具体代码如下:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;
int BinarySearch(int a[],int x,int low,int high)//二分查找
{
if(low>high)
return -1;
int mid=(low+high)/2;
if(x==a[mid])
return mid;
if(x<a[mid])
return BinarySearch(a,x,low,mid-1);
return BinarySearch(a,x,mid+1,high);
}
int main()
{
int temp=1,l,m,n;
while(scanf("%d%d%d",&l,&m,&n)!=EOF)
{
int i;
int *a,*b,*c;
a=(int*)malloc(sizeof(int)*l);
b=(int*)malloc(sizeof(int)*m);
c=(int*)malloc(sizeof(int)*n);
for(i=0;i<l;i++)
cin>>a[i];
for(i=0;i<m;i++)
cin>>b[i];
for(i=0;i<n;i++)
cin>>c[i];
int s;
cin>>s;
int *h;
h=(int *)malloc(sizeof(int)*s);
for(i=0;i<s;i++)
cin>>h[i];
int *p;//储存最终结果
p=(int *)malloc(sizeof(int)*(m*n));
int j,k,q=0;
for(j=0;j<m;j++)
for(k=0;k<n;k++)
p[q++]=b[j]+c[k];
sort(p,p+q);//升序排序
printf("Case %d:\n",temp);
temp++;
int flag;
for(i=0;i<s;i++)
{
for(flag=0,j=0;j<l;j++)
{
if(BinarySearch(p,h[i]-a[j],0,m*n-1)!=-1)
{
flag=1;
break;
}
}
if(flag==1)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
}
return 0;
}