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

思路:枚举三个数组,时间复杂度O(N^3),肯定会超时。所以可以把前两个数组的和先枚举出来,存在数组sum[260000]中,

由于要找是否存在sum[i] + c[j] = X, 可以把问题转换为在sum数组中查找是否有X-c[j]这个数。用二分查找sum数组即可。时间复杂度为: S * c数组的大小 * log(sum数组的大小)

注意:不能在c数组中二分查找是否有X-sum[i]这个数,因为其时间复杂度为: S * sum数组的大小 * log(c数组的大小),由于题目中sum数组大小最大为250000,c数组大小最大为500,S为1000,所以会超时

 #include <iostream>
#include <queue>
#include <cstring>
#include <cstdio>
#include <string>
#include <algorithm> using namespace std; int a[], b[], c[];
int sum[];
int L, N, M, S, X;
int cnt = ; int main()
{
while(scanf("%d %d %d", &L, &N, &M) != EOF)
{
for(int i = ; i < L; ++i)
scanf("%d", &a[i]);
for(int i = ; i < N; ++i)
scanf("%d", &b[i]);
for(int i = ; i < M; ++i)
scanf("%d", &c[i]); int k = ;
for(int i = ; i < L; ++i)
for(int j = ; j < N; ++j)
sum[k++] = a[i] + b[j]; sort(sum, sum+k);
scanf("%d", &S);
printf("Case %d:\n", cnt++);
while(S--)
{
scanf("%d", &X); int flag = ;
for(int i = ; i < M; ++i)
{
int target = X - c[i];
int left = , right = k; while(left <= right)
{
int mid = (left + right) / ;
if(sum[mid] == target)
{
flag = ;
break;
}
else if(sum[mid] < target)
left = mid + ;
else
right = mid - ;
}
if(flag == )
{
printf("YES\n");
break;
}
}
if(flag == )
printf("NO\n"); }
} return ;
}
04-25 17:12
查看更多