题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2141
题意:
给定三个有序整数序列A、B、C和一个整数X,你能否找到一组Ai、Bj、Ck满足等式:Ai+Bj+Ck = X。
输入:可有多组输入实例。第一行有三个整数L、M、N,第二行是序列A中的L个有序整数,第三行是序列B中的M个有序整数,第四行是序列C中的N个有序整数。第五行是整数S,表示有S个X需要计算。1<=L, N, M<=500, 1<=S<=1000. 所有整数均为32位整数。
输出:对每一组测试实例,首先要输出“Case d:”,其中d为测试实例的序号,然后根据是否满足等式,输出NO(不满足),或YES(满足)。
输入
3 3 3
1 2 3
1 2 3
1 2 3
3
1
4
10
输出
Case 1:
NO
YES
NO
思路:
最容易想到的是三重for遍历 ,但商品数最大 = 500,红包数最多 = 1000;但1e3*500^3 必然超时;
二分,先确定两个,再用二分查找第三个,1e3*500^2 = 2.5e8 超时;
因此这里我的办法是先将一组数的所有数和另一组数的所有数两两相加,存到一个数组sum里,最多:500*500=2.5e5,
最后先确定第三组数里的一个数,用二分查找sum数组,看能否找到一个数使得相加结果为X,
最多运算次数1000*500* log(2.5e5)≈ 7e6
AC代码
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int RPM = 1005;
const int SM = 505;
bool BS(long long int a[],int size,int tof)
{
int l=0;
int r=size-1;
while(l <= r) {
int mid = l+(r-l)/2;
if(a[mid] == tof)
return true;
else {
if(a[mid] > tof)
r = mid-1;
else
l = mid+1;
}
}
return false;
}
int main()
{
int L,M,N,H;
long long int a[SM],b[SM],c[SM],sum[SM*SM];
int Case = 1;
while(scanf("%d %d %d",&L,&M,&N)!= EOF) {
for(int i=0;i<L;i++)
scanf("%lld",&a[i]);
for(int i=0;i<M;i++)
scanf("%lld",&b[i]);
for(int i=0;i<N;i++)
scanf("%lld",&c[i]);
int k=0;
for(int i=0;i<L;i++)
for(int j=0;j<M;j++)
sum[k++] = a[i] + b[j];
sort(sum,sum+L*M);
printf("Case %d:\n",Case++);
scanf("%d",&H);
while(H--) {
int flag=0;
int Count;
scanf("%d",&Count);
for(int i=0;i<N;i++) {
if( BS(sum,L*M,Count-c[i])) {
flag = 1;
break;
}
}
if( flag)
printf("YES\n");
else
printf("NO\n");
}
}
}