1. 程式人生 > >HDU - 2141 : Can you find it?

HDU - 2141 : Can you find it?

sizeof sin case uniq utf first ted 整數 代碼

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?