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.
3 3 3 1 2 3 1 2 3 1 2 3 3 1 4 10
Sample Output
Case 1: NO YES NO
题目大意:给你三个数组A,B,C。问能不能再A,B,C数组中各找一个数使得他们的和为X里。
从数据范围来看A,B,C数组都不超过500个,但是暴力的话复杂度为n^3 空间与时间复杂度难以接受。
换个思路,将A,B数组合并为数组D,那么问题就变成了Di+Ci=X
即X-Di=Ci
枚举D数组中的元素并在C数组中进行二分查找。
依然是思路的问题。我们看到500^3难以接受,但是500*500很好实现,自己的榆木脑袋还是有待雕琢呀。。。
源代码:
#include<iostream>
#include <algorithm>
using namespace std;
int main()
{
int l,n,m,total=0;
while (cin>>l>>n>>m)
{
total++;
int tot=0,s;
int a[505];int b[505];int c[505];int d[260000];
for (int i=1;i<=l;i++) cin>>a[i];
for (int i=1;i<=n;i++) cin>>b[i];
for (int i=1;i<=m;i++) cin>>c[i];
cin>>s;
for (int i=1;i<=l;i++)
for (int j=1;j<=n;j++)
{
tot++;
d[tot]=a[i]+b[j];
}
sort(d+1,d+tot+1);
cout<<"Case "<<total<<":"<<endl;
for (int i=1;i<=s;i++)
{
bool flag=false;
int k;
cin>>k;
for (int j=1;j<=m;j++)
{
int l=1,r=tot,mid;
int ans=k-c[j];
while (l<=r)
{
mid=(l+r)/2;
if (d[mid]==ans)
{
flag=true;break;
}
if (d[mid]<ans) l=mid+1;
if (d[mid]>ans) r=mid-1;
}
if (flag) break;
}
if (flag) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
}
return 0;
}