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
暴力枚举,0(n^3)爆炸。
枚举前两个数,二分第三个O(n^2logn)
貌似也可能爆炸
先处理前两个数的和O(n^2)
排序,之后枚举第三个数
二分后两个数的和O(nlogn)
故复杂度为O(n^2)可以通过数据。
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int main()
{
int l,n,m;
int p=1;
while(~scanf("%d%d%d",&l,&n,&m))
{
int a[510];
int b[510];
int c[510];
long long ab[250005];
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]);
long long k=0;
for(int i=0; i<l; i++)
{
for(int j=0; j<n; j++)
{
ab[k++]=a[i]+b[j];
}
}
sort(ab,ab+k);
#include<string.h>
#include<algorithm>
using namespace std;
int main()
{
int l,n,m;
int p=1;
while(~scanf("%d%d%d",&l,&n,&m))
{
int a[510];
int b[510];
int c[510];
long long ab[250005];
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]);
long long k=0;
for(int i=0; i<l; i++)
{
for(int j=0; j<n; j++)
{
ab[k++]=a[i]+b[j];
}
}
sort(ab,ab+k);
printf("Case %d:\n",p++);
int jj,j;
scanf("%d",&jj);
while(jj--)
{
scanf("%d",&j);
int sign=0;
for(int i=0; i<m; i++)
{
int xiao=0,da=k-1;
int zhong=0;
while(xiao<=da)//重点理解二分
{
zhong=(xiao+da)/2;//直接从中间开始判断
if(ab[zhong]+c[i]==j)//如果其值正好与所求值相等
{
sign=1;//sign标记为1
break;//结束while循环
}
if(ab[zhong]+c[i]<j)//其值小于所求值
xiao=zhong+1;//小值赋值为“其值”加1
if(ab[zhong]+c[i]>j)//其值大于所求值
da=zhong-1;//大值赋值为“其值”减1
}
if(sign==1)//sign为1,表明有一个值等于所求值,结束for循环
break;
}
if(sign==1)
printf("YES\n");
else
printf("NO\n");
int jj,j;
scanf("%d",&jj);
while(jj--)
{
scanf("%d",&j);
int sign=0;
for(int i=0; i<m; i++)
{
int xiao=0,da=k-1;
int zhong=0;
while(xiao<=da)//重点理解二分
{
zhong=(xiao+da)/2;//直接从中间开始判断
if(ab[zhong]+c[i]==j)//如果其值正好与所求值相等
{
sign=1;//sign标记为1
break;//结束while循环
}
if(ab[zhong]+c[i]<j)//其值小于所求值
xiao=zhong+1;//小值赋值为“其值”加1
if(ab[zhong]+c[i]>j)//其值大于所求值
da=zhong-1;//大值赋值为“其值”减1
}
if(sign==1)//sign为1,表明有一个值等于所求值,结束for循环
break;
}
if(sign==1)
printf("YES\n");
else
printf("NO\n");
}
}
return 0;
}
}
return 0;
}