HDU2141Can you find it? (二分计算计算Ai+Bj+Ck = X)

Can you find it?
Time Limit: 10000/3000 MS (Java/Others)    Memory Limit: 32768/10000 K (Java/Others)
Total Submission(s): 13756    Accepted Submission(s): 3536
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


 
Author
wangye
 
Source
HDU 2007-11 Programming Contest
 
Recommend
威士忌   |   We have carefully selected several similar problems for you:  2899 2289 1597 1551 2298 

题意:计算Ai+Bj+Ck = X.
思路:将A和B的值合并为一个值,构成一个新的序列,key=X-C,再在新序列中用二分查找key

注意:1.排序(x<y是升序),,排序默认也为升序

            2.二分时比较后可以跳过比较mid,直接比较mid-1,mid+1

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std;
int d[250005];

int cmp(int a,int b)
{
    return a<b;
}

int erfen(int n,int key)
{
    int left=0,right=n-1,mid;
    while(left<=right)
    {
        mid=(left+right)/2;
        if(d[mid]<key)
        left=mid+1;
        else if(d[mid]>key)
        right=mid-1;
        else
        return 1;
    }
    return 0;
}

int main()
{
    int l,n,m,s,key,f,num=0;
    int a[505],b[505],c[505],ss[1005];
    while(~scanf("%d%d%d",&l,&n,&m))
    {
        num++;
        for(int i=0;i<l;i++)
        scanf("%d",&a[i]);
        for(int j=0;j<n;j++)
        scanf("%d",&b[j]);
        for(int k=0;k<m;k++)
        scanf("%d",&c[k]);
        int g=0;
        for(int i=0;i<l;i++)
        for(int j=0;j<n;j++)
        {
            d[g++]=a[i]+b[j];
        }
        sort(d,d+g,cmp);
        //sort(d,d+g);(排序默认为升序)
        scanf("%d",&s);
        printf("Case %d:\n",num);
       while(s--)
       {
           f=0;
           scanf("%d",&key);
            for(int i=0;i<m;i++)
            {
                if(erfen(l*n,key-c[i]))
                {
                   // printf("!!!!\n");
                    f=1;
                    break;
                }
            }
            if(f==0)
            printf("NO\n");
            else
            printf("YES\n");

        }
    }
    return 0;
}

posted @ 2015-08-22 18:06  Lincy*_*  阅读(405)  评论(0编辑  收藏  举报