ACM暑假集训_二分&三分_A-Can you find it?
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
Hint
解题思路
有3个数表,问有多少种从3数表各选一个数的组合, 可以使得3个数的和加起来等于M。
直接每个组合方式都试一次然后判断时间复杂度太大,所以要有其他方法。
先将2,3个数表的全部数字相加,排序,然后再用二分法和第一个数表中的数字组合。
代码
#include <iostream>
#include<algorithm>
using namespace std;
int main()
{
int L,N,M,S,X,m=1,s,min,max;
int A[501],B[501],C[501],K[300000];
while(cin>>L>>N>>M)
{
for(int i=0;i<L;i++)
{
cin>>A[i];
}
for(int i=0;i<N;i++)
{
cin>>B[i];
}
for(int i=0;i<M;i++)
{
cin>>C[i];
}
int k=0;
for(int i=0;i<N;i++)
{
for(int j=0;j<M;j++)
{
K[k++]=B[i]+C[j];
}
}
sort(K,K+k);
sort(A,A+L);
cin>>S;
cout<<"Case "<<m++<<":"<<endl;
while(S--)
{
cin>>X;
int flag=0;
for(int i=0;i<L;i++)
{
int left=1,right=k-1;
while(left<=right)
{
int mid=(right+left)/2;
if(K[mid]+A[i]==X)
{
flag=1;
break;
}
else if(K[mid]+A[i]<X)
{
left=mid+1;
}
else
{
right=mid-1;
}
}
}
if(flag==1)
{
cout<<"YES"<<endl;
}
else
{
cout<<"NO"<<endl;
}
}
}
return 0;
}