A - Can you find it?

本文介绍了一种解决三数求和问题的有效算法。通过将两个数相加形成的新序列与第三个序列进行匹配来判断是否存在三个数之和等于指定目标值。文章提供了完整的C++实现代码,并使用二分查找来提高搜索效率。
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
最先想到的是枚举,但无奈的是超时了,然后看想到二分,这有三序列,一直没找到思路,后来一查,原来把前两个序列逐个相加得到新的序列然后排序,与剩下的序列去相匹配。看来在书上看懂了算法不一定就一定能运用好
#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;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值