HDU 2141 Can you find it? (二分查找)

来源:互联网 发布:看三维彩超数据分男女 编辑:程序博客网 时间:2024/05/28 18:43

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 31 2 31 2 31 2 331410
 

Sample Output
Case 1:NOYESNO
 

#include <iostream>

#include <string.h>
#include <algorithm>
#include <stdio.h>
using namespace std;
bool Search(long long Sum[],int low,int high,int value)
{
    while(low<=high)
    {
        int mid=(low+high)/2;
        if(Sum[mid]==value)return true;
        else if(Sum[mid]<value)low=mid+1;
        else high=mid-1;
    }
    return false;
}
int main()
{
    int cases=0;
    int L,N,M;
    while(cin>>L>>N>>M)
    {
        int A[510]={0},B[510]={0},C[510]={0},S,X;
        long long Sum[250010]={0},len=0;
        for(int i=0;i<L;i++)
            cin>>A[i];
        for(int i=0;i<N;i++)
            cin>>B[i];
        for(int i=0;i<M;i++)
            cin>>C[i];
        for(int i=0;i<N;i++)//计算A与B所有元素之和
            for(int j=0;j<M;j++)
            Sum[len++]=A[i]+B[j];
        sort(Sum,Sum+len);//排序以便二分查找
        sort(C,C+M);
        cout<<"Case "<<++cases<<":"<<endl;
        cin>>S;
        while(S--)
        {
            cin>>X;
            if(Sum[0]+C[0]>X||Sum[len-1]+C[M-1]<X)
            {
                cout<<"NO"<<endl;
                continue;
            }
            int flag=0;
            for(int i=0;i<M;i++)
            {
                int temp=X-C[i];
                if(Search(Sum,0,len-1,temp)==true)//一旦找到就OK
                {
                    cout<<"YES"<<endl;
                    flag=1;
                    break;
                }
            }
            if(flag==0)
                cout<<"NO"<<endl;
        }
    }
    return 0;
}


0 0
原创粉丝点击