1. 程式人生 > >HDU 2141 Can you find it?(二分)

HDU 2141 Can you find it?(二分)

clas i++ clu div cpp style [] href ++

題目鏈接:clicl here~~

【題目大意】:

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.

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 
【解題思路】將前兩個數組元素合並為一個,在和最後一個進行選擇。二分合並後的數組,假設

if(sort[mid]<ans) left=mid+1;
else if(sort[mid]>ans) right=mid-1;
else {flag=true;break;}

代碼:

#include <bits/stdc++.h>
using namespace std;
const int N=505;
int A[N],B[N],C[N],D[N*N];
bool get(int sort[],int k,int ans)//合並後的數組/數組元素個數/和減去第三個數組元素剩下的值
{
    bool flag=false;
    int left=0,right=k,mid;
    while(left<=right)
    {
        mid=(left+right)>>1;
        if(sort[mid]<ans) left=mid+1;
        else if(sort[mid]>ans) right=mid-1;
        else {flag=true;break;}
    }
    return flag;
}
int main()
{
    //freopen("1.txt","r",stdin);
    int l,n,z,m,S,tot=1;
    bool ok;
    while(scanf("%d%d%d",&l,&n,&m)!=EOF)
    {
        for(int i=0;i<l;i++) scanf("%d",&A[i]);
        for(int i=0;i<n;i++) scanf("%d",&B[i]);
        for(int i=0;i<m;i++) scanf("%d",&C[i]);
        int k=0;
        for(int i=0;i<l;i++)
        for(int j=0;j<n;j++) D[k++]=A[i]+B[j];
        sort(D,D+k);
        scanf("%d",&S);
        printf("Case %d:\n",tot++);
        while(S--)
        {
            ok=false;
            scanf("%d",&z);
            for(int i=0;i<m;i++){
            if(get(D,k,z-C[i])) {ok=true;break;}
            }
            if(ok) puts("YES");
            else puts("NO");
        }
    }
    return 0;
}


HDU 2141 Can you find it?(二分)