HDU - 2141 Can you find it? 二分查找

HDU - 2141 Can you find it?
题目描述:
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
题目大意:就是给你三个序列,然后给你一个数,在三个序列中各找一个数,使得找的这三个数等于所给数,找得到输出“YES”,不然输出“NO”

思路:暴力当然能找得到,但是时间复杂度就是LMNS,毋庸置疑。。。超时的
找数嘛,想到二分,就是先在把两个序列合成一个序列,然后再查找,这样复杂度就降下来了!记得先sort一下
不多说,上代码!!!

#include <iostream>
#include <set>
#include <algorithm>
#include <vector>
using namespace std;
int l , n , m , s , x;
int a[510];
int b[510];
int c[510];
int sum[250010];

int main(){
    int w = 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]);  
        }
        int k = 0;
        for(int i = 0 ; i < l ; ++i){
            for(int j = 0 ; j < n;++j){
                sum[k++] = a[i] + b[j]; 
            }
        }
        sort(sum,sum+k);
        for(int i = 0 ; i < m ; ++i){
            scanf("%d",&c[i]);  
        }
        sort(c,c+m);
        scanf("%d",&s);

        printf("Case %d:\n",w);
        w++;

        for(int i = 0 ; i < s ; ++i){
            scanf("%d",&x);
            bool flag = false;
            for(int j = 0; j < m ;++j){ 
                int temp = x - c[j];
                int low = 0 , high = k - 1;
                int mid;
                while(low <= high){
                    mid = (low + high) / 2;
                    if(sum[mid] > temp){
                        high = mid-1;
                    }
                    else if(sum[mid] < temp){
                        low = mid+1;
                    }
                    else{
                        flag = true;
                        break;
                    }
                }

                if(flag){
                    printf("YES\n");
                    break;
                }
            }
            if(!flag)   printf("NO\n");
        }
    }
    return 0;
} 

猜你喜欢

转载自blog.csdn.net/Love_Yourself_LQM/article/details/81709026
今日推荐