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,n,m长度的串,从每个串中取一个数相加,若能得到给出数的和,则YES,否则NO
思路:刚开始写的三层for循环,然后map存三个串能得到的所有和,然后爆内存……
正确的思路是先将前两个for循环求出和得到一个新的数组,sort排序,遍历第三个串,从得到的新串中二分寻找答案
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
#include<map>
#include<vector>
using namespace std;
const int MAXN=500+10;
//const int inf=0x3f3f3f;
long long x[MAXN],y[MAXN],z[MAXN];
long long s[MAXN*MAXN];
int l,n,m;
int judge(long long p,long long answer,int left,int right)
{
while(left<=right)
{
int mid=(left+right)/2;
if(s[mid]+p==answer)
return 1;
else if(s[mid]+p<answer)
left=mid+1;
else if(s[mid]+p>answer)
right=mid-1;
}
return 0;
}
int main()
{
int t=0;
while(~scanf("%d%d%d",&l,&n,&m))
{
for(int i=0; i<l; i++)
scanf("%lld",&x[i]);
for(int i=0; i<n; i++)
scanf("%lld",&y[i]);
for(int i=0; i<m; i++)
scanf("%lld",&z[i]);
int k=0;
memset(s,0,sizeof(s));
long long ans;
for(int i=0; i<l; i++)
{
for(int j=0; j<n; j++)
{
s[k++]=x[i]+y[j];
}
}
sort(s,s+k);
int p;
scanf("%d",&p);
long long a;
printf("Case %d:\n",++t);
while(p--)
{
scanf("%lld",&a);
int flag=0;
for(int i=0; i<m; i++)
{
if(judge(z[i],a,0,k-1))
{
flag=1;
break;
}
}
if(!flag) printf("NO\n");
else if(flag==1) printf("YES\n");
}
}
}