Can you find it? 分类: 二分查找 2015-06-10 19:55 5人阅读 评论(0) 收藏

时间:2023-03-09 07:46:31
Can you find it?                                                    分类:            二分查找             2015-06-10 19:55    5人阅读    评论(0)    收藏

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

一开始TLE因为是三个for循环在一起,后来将两个for循环分开就没TLE了

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstdlib>
int n,m,l,t,f,tmp,q;
using namespace std;
int a[1000],b[1000],c[1000],d[2555555];
int main()
{int cnt=0;
while(~scanf("%d%d%d",&l,&n,&m))
{f=0;
for(int i=0;i<l;i++)
scanf("%d",&a[i]);
for(int i=0;i<n;i++)
scanf("%d",&b[i]);
for(int i=0;i<m;i++)
scanf("%d",&c[i]);
int y=0;
for(int j=0;j<l;j++)
for(int k=0;k<n;k++)
d[y++]=a[j]+b[k];
sort(d,d+y);
scanf("%d",&t);
printf("Case %d:\n",++cnt);
while(t--)
{scanf("%d",&tmp);
for(int i=0;i<m;i++)
{q=tmp-c[i];
int low=0;
int high=y-1;
int mid=(y-1)/2;
while(low<high)
{
if(d[mid]==q)
{f=1;
break;}
if(d[mid]<q)
low=mid+1;
if(d[mid]>q)
high=mid-1;
mid=(high+low)/2;
}
if(d[low]==q || d[high]==q) f=1;
if(f)
break;}
if(f==1)
printf("YES\n");
else
printf("NO\n");
f=0;
}}
return 0;
}