can you find it?

来源:互联网 发布:淘宝收货了怎么退货 编辑:程序博客网 时间:2024/05/01 09:29
A - Can you find it?

Time Limit:3000MS     Memory Limit:10000KB     64bit IO Format:%I64d & %I64u

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


这道题是要求从三组数中各取一个数使之和等于给定的x,暴力求解的话用三重循环,时间复杂度太大。用二分法求解:将A、B两组中的数两两组合相加存到一个新数组中,从C出发一层循环:以和为x为条件对新数组进行二分查找。

启示遇到在一个区间段内对某固定值进行查找的问题时,可以想办法把问题变形以应用二分法


代码:

<span style="font-family:Microsoft YaHei;font-size:14px;">#include<cstdio>#include<cstring>#include <algorithm>using namespace std;int n1,n2,n3,n4,T,x;int cas=1;int main(){    while(scanf("%d%d%d",&n1,&n2,&n3)!=EOF){    int a[510],b[510],c[510],p[251000];        for(int i=0;i<n1;i++)            scanf("%d",&a[i]);        for(int i=0;i<n2;i++)            scanf("%d",&b[i]);        for(int i=0;i<n3;i++)            scanf("%d",&c[i]);    printf("Case %d:\n",cas++);    memset(p,0,sizeof(p));    int f=0;    for(int i=0;i<n1;i++)         for(int j=0;j<n2;j++)                p[f++]=a[i]+b[j];    sort(p,p+f);    scanf("%d\n",&n4);    while(n4--){    scanf("%d",&x);    int l,r,mid;    int mark=0;    for(int i=0;i<n3;i++){    l=0;    r=f-1;        while(l<=r){            mid=(l+r)/2;            if(c[i]+p[mid]==x){                printf("YES\n");                mark=1;                break;}            else if(c[i]+p[mid]>x)                r=mid-1;            else                l=mid+1;            }        if(mark!=0)            break;        }    if(mark==0)         printf("NO\n");    }    }    return 0;}</span>


0 0
原创粉丝点击