Can you find it? 【二分】

本文探讨了一个经典的算法问题——给定三个数列A、B、C及目标数X,判断是否存在A[i] + B[j] + C[k] = X。通过预处理A+B的所有可能组合,并使用二分查找来提高搜索效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

记得 白书上好像有和这个类似的。 就是要先将式子变下形,
A+B = X-C ;
并且让A+B 合在一个数组里; 【不是很难,不过一定要理解这个二分枚举】
代码

#include<bits/stdc++.h>
#define LL long long
using namespace std;
const int MAXN = 500+10;
const int MAXM = 3000000;
const int inf = 0x3f3f3f3f;
const double pi= acos(-1.0);
const double eps = 1e-5;
/*------------------------------*/
int l,n,m;
int a[MAXN],b[MAXN],c[MAXN];
int d[MAXM];
int main(){
    int kk=1;
    while(~scanf("%d%d%d",&l,&n,&m)){
        for(int i=0;i<l;i++)
            scanf("%d",&a[i]);
        for(int i=0;i<n;i++)
            scanf("%d",&b[i]);
        for(int i=0;i<m;i++)
            scanf("%d",&c[i]);
             printf("Case %d:\n",kk++);
            int s=0;
        for(int i=0;i<l;i++){
            for(int j=0;j<n;j++){
                 d[s++]=a[i]+b[j];
            }
        }
        int ri=s;
        sort(d,d+s);
        int q;cin>>q;
        while(q--){
        int a;scanf("%d",&a);
            int i;   int mid;
            for(i=0;i<m;i++){
                int o=a-c[i];
                int L=0;int R=ri-1;
                int ss;
                while(L<=R){
                    mid=(L+R)>>1;
                    if(d[mid]>=o) { ss=d[mid]; R=mid-1;}
                    else L=mid+1;
                }
                //printf("ss=== %d \n",ss);
                if(ss==o) break;
            }
            if(i==m) puts("NO");
            else puts("YES");
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值