Can you find it?

本文详细解析了一道ACM竞赛经典题目——三序列求和问题。该问题要求判断是否存在三个数,分别来自三个不同的序列,使得它们的和等于给定的目标数。通过输入三个序列和目标数,利用预处理和二分查找算法,高效地解决这一问题。代码示例使用C++实现,展示了如何遍历所有可能的组合并排序,然后应用二分查找来验证目标数的存在。

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

Can you find it? ACM

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 C,每个数组中分别有3,3,3个数,让后每个数组中的数分别为A:1,2,3 B:1,2,3、C:1,2,3。让后现在有S组测试数据。
首先将数据都输入进去,对所输入的数据进行相加再排序,共有A* B* C种情况,让后利用二分法(不懂二分的话,可以看一下我的另一篇讲二分的博客),看所要找的数是否在这些情况中。如果可以找到,输入yes,如果不行,就输出no。

#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
void ff(int *p,int key,int l)
{
    int a=0,mid;
    mid=l/2;
    while(a<l&&p[mid]!=key)
    {
        if(p[mid]>key)
        {
            l=mid-1;
        }else
        {
            a=mid+1;
        }
        mid=(l+a)/2;
    }
    if(p[mid]==key)
    {
        printf("YES\n");
    }
    else
    {
        printf("NO\n");
    }
}
int main()
{
    int a,b,c,y=1;
    while(~scanf("%d%d%d",&a,&b,&c))
    {
        int A[510],B[510],C[510];
        for(int i=0;i<a;i++)
        {
            scanf("%d",&A[i]);
        }
        for(int i=0;i<b;i++)
        {
            scanf("%d",&B[i]);
        }
        for(int i=0;i<c;i++)
        {
            scanf("%d",&C[i]);
        }
        int d,e=a*b*c,f=0,D[110],E[e];
        scanf("%d",&d);
        for(int i=0;i<d;i++)
        {
            scanf("%d",&D[i]);
        }
        for(int i=0;i<a;i++)
        {
            for(int j=0;j<b;j++)
            {
                for(int k=0;k<c;k++)
                {
                    E[f]=A[i]+B[j]+C[k];
                    f++;
                }
            }
        }
        sort(E,E+e);
        printf("Case:%d\n",y);
        y++;
        for(int i=0;i<d;i++)
        {
          ff(E,D[i],e);
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值