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 先暴力求解出所有 Ai + Bj,然后二分查找 X – Ck 时间复杂度就是O(n^2logn)。 代码
#include <cstdio>
#include <iostream>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <string>
#include <queue>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
#define MAXN 505
long long  A[MAXN],B[MAXN],C[MAXN],S[MANX*MAXN];
int num;
bool search(long long p)
{
    int l=0,r=num-1;
    int mid;
    while (r>=l)
    {
        mid=(r+l)/2;
        if (S[mid]==p)
            return true;
        else if(S[mid]<p)
            l=mid+1;
        else
            r=mid-1;
    }
    return 0;
}
int main ()
{
    int L,M,N,s,ca=0;
    long long x;
    int i,j;
    while (scanf ("%d%d%d",&L,&M,&N)!=EOF)
    {
        for (i=0;i<L;i++)
            scanf ("%I64d",&A[i]);
        for (i=0;i<M;i++)
            scanf ("%I64d",&B[i]);
        for (i=0;i<N;i++)
            scanf ("%I64d",&C[i]);
        num=0;
        for (i=0;i<L;i++)
            for (j=0;j<M;j++)
                S[num++]=A[i]+B[j];
        sort (S,S+num);
        sort (C,C+N);
        scanf ("%d",&s);
        printf ("Case %d:\n",++ca);
        while (s--)
        {
            scanf ("%I64d",&x);
            if(x<S[0]+C[0]||x>S[num-1]+C[N-1])
            {
                printf ("NO\n");
            }
            else
            {
                int mm;
                for (mm=0;mm<N;mm++)
                {
                    long long p=x-C[mm];
                    if(search(p))
                    {
                        printf ("YES\n");
                        break;
                    }
                }
                if(mm==L)
                    printf ("NO\n");
            }

        }
    }
    return 0;
}




评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值