HDU - 2141 : Can you find it?

Posted 西北会法语

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU - 2141 : Can you find it?相关的知识,希望对你有一定的参考价值。

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
10

Sample Output

Case 1:
NO
YES
NO

给三组整数,在下面每给一个整数,判断从三组数各取一个相加与此整数是否可以相等。
直接暴力复杂度为O(N^3),不可行。可以将前两组枚举,复杂度为O(N^2),再排序,对于每一个目标数,枚举第三组数,二分查找前两组的和即可。

源代码:
#include<iostream>
#include<algorithm>
#include<string.h>

using namespace std;

int a[505],b[505],c[505],d[250005];

int main() {
int L,M,N,S,s=1,x,y,z,flag;
while(cin>>L>>M>>N)
{
y=0;
flag=0;
cout<<"Case "<<s++<<":"<<endl;
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));
memset(d,0,sizeof(d));
for(int i=0;i<L;i++)
cin>>a[i];
for(int i=0;i<M;i++)
cin>>b[i];
for(int i=0;i<N;i++)
{
cin>>c[i];
for(int j=0;j<M;j++)
d[y++]=c[i]+b[j];
}
sort(d,d+y);
int ans=unique(d,d+y)-d;
/*cout<<ans<<" "<<y; for(int i=0;i<y;i++) cout<<d[i]<<endl;*/

cin>>S;
for(int i=0;i<S;i++)
{
cin>>x;
flag=0;
for(int j=0;j<L;j++)
{
z=x-a[j];
if(binary_search(d,d+ans,z))
{
flag=1;
break;
}
}
if(flag)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
}

return 0;
}

以上是关于HDU - 2141 : Can you find it?的主要内容,如果未能解决你的问题,请参考以下文章

HDU 2141 Can you find it? 二分查找

HDU 2141 Can you find it? (二分)

hdu2141Can you find it?

HDU - 2141 Can you find it?(二分)

HDU 2141 can you find it 二分

hdoj-2141-Can you find it?