hdu-2141 Can you find it?

题目链接:
https://vjudge.net/problem/HDU-2141

Can you find it?

Problem Description
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

这道题题目的意思就是给你三个数组,然后再给你一个数X,让你判断在这三个数组中是否分别存在一个数使得他们的和为y,即a[i]+b[j]+c[k]=X。

这题的题面意思很好理解,我一开始想到的就是用暴力解决,用三重for循环来模拟寻找这三个数的过程,但是每重for循环都是循环到500,所以超时了,那时候也T了好几发。
后来我想到了用二分法来解决,但是实力还太弱,没想到要怎么进行二分,比赛完后和大佬们交流才知道可以先把前面两个数组相加,将其合并为一个新的数组 AB;此时,因为我们是要求 A+B+C=X,可以变一下得到 A+B=X-C,即 AB=X-C。接着就是对 X-C 进行二分搜索。

AC代码:

#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<math.h>
#include<iostream>
#include<string>
using namespace std;
int a[505],b[505],c[505];
int num[251000];
int bSearch(int num[], int n, int k)     //二分查找
{
    int mid,left=1,right=n;
    while(left<=right)
    {
        mid=(left+right)/2;
        if(num[mid]==k) return mid;
        if(num[mid]>k) right=mid-1;
        else left=mid+1;
    }
    return 0;
}
int main()
{
    int l,n,m,T=1;
    while(cin>>l>>n>>m)
    {
        int cnt=0;
        for(int i=0; i<l; ++i)
            cin>>a[i];
        for(int j=0; j<n; ++j)
            cin>>b[j];
        for(int k=0; k<m; ++k)
            cin>>c[k];
        for(int i=0; i<l; ++i)
        {
            for(int j=0; j<n; ++j)
            {
                num[cnt++]=a[i]+b[j];
            }
        }
        sort(num,num+cnt);
        int t;
        cin>>t;
        cout<<"Case "<<T++<<":"<<endl;
        while(t--)
        {
            int flag=1;
            int x;
            cin>>x;
            for(int i=0; i<m; ++i)
            {
                int en=x-c[i];
                if(bSearch(num,cnt,en))
                {
                    flag=0;
                    break;
                }
            }
            if(flag==0)
                cout<<"YES"<<endl;
            else
                cout<<"NO"<<endl;
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44137005/article/details/88952496