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
Sample Output
Input
3 3 3 1 2 3 1 2 3 1 2 3 3 1 4 10
Case 1: NO YES NO
最先想到的是枚举,但无奈的是超时了,然后看想到二分,这有三序列,一直没找到思路,后来一查,原来把前两个序列逐个相加得到新的序列然后排序,与剩下的序列去相匹配。看来在书上看懂了算法不一定就一定能运用好
#include<iostream>
#include<algorithm>
using namespace std;
int bf(int sum[],int k,int x)
{
int low=0,mid,high=k-1;
while(low<=high){
mid=(low+high)>>1;//相当与除以2;
if(sum[mid]==x)return 1;
else if(sum[mid]<x)low=mid+1;
else high=mid-1;
}
return 0;
}
int main()
{
int A[510],B[510],C[510],sum[500*500];int a,b,c,k,flag,t=0;
while(cin>>a>>b>>c){k=0;
for(int i=0;i<a;i++)cin>>A[i];
for(int i=0;i<b;i++)cin>>B[i];
for(int i=0;i<c;i++)cin>>C[i];
for(int i=0;i<a;i++){
for(int j=0;j<b;j++)sum[k++]=A[i]+B[j];
}
sort(sum,sum+k);//for(int i=0;i<k;i++)cout<<sum[i];
cout<<"Case "<<++t<<":\n";
int s;cin>>s;
while(s--){
int x;cin>>x;flag=0;
for(int i=0;i<c;i++){
if(bf(sum,k,x-C[i])){flag=1;break;}
}
if(flag)cout<<"YES\n";
else cout<<"NO\n";
}
}
return 0;
}
本文介绍了一种解决三数求和问题的有效算法。通过将两个数相加形成的新序列与第三个序列进行匹配来判断是否存在三个数之和等于指定目标值。文章提供了完整的C++实现代码,并使用二分查找来提高搜索效率。
4万+

被折叠的 条评论
为什么被折叠?



