O

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
 
AC代码:
#include <iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>//排序的头文件
using namespace std;
int  a[501],b[501],c[501],d[501*501];//合并数组的范围应为之前数组的平方
int main()
{
    int l,n,m,i,j,k,p,y,s,x;
     s=0;
    while(scanf("%d%d%d",&l,&n,&m)!=EOF)
    {
        for(i=0;i<l;i++)
        scanf("%d",&a[i]);
    for(i=0;i<n;i++)
        scanf("%d",&b[i]);
    for(i=0;i<m;i++)
        scanf("%d",&c[i]);
        sort(c,c+m);//将数组进行排序
        int q=0;
        for(j=0;j<n;j++)
            for(k=0;k<m;k++)
            d[q++]=a[j]+b[k];//将前两个数组求和,合并成为一个数组
       sort(d,d+q);
       scanf("%d",&p);
       printf("Case %d:
",++s);//此处少写了换行符
             for(i=0;i<p;i++)
             {
                  scanf("%d",&x);
                  int flag=0;//标记
                  for(k=0;k<m;k++)
                  {
                      y=x-c[k];
                      int le,r,mid;
                      le=0;//左端点
                      r=q-1;//右端点,刚写错了,将区间的范围缩小了
                      while(le<=r)//二分法核心代码
                      {
                          mid=(le+r)/2;//中区间
                       if(y==d[mid])
                       {
                           flag=1;
                           break;//终止判断
                       }
                       if (d[mid]<y)
                           le=mid+1;
                       else r=mid-1;
                  }
                  if(flag==1) break;//如果有一个合法的y就结束循环
                      }
                  if(flag)
                    printf("YES
");
                  else printf("NO
");
             }
    }
    return 0;
}
分析:就是给你ABC三个数,这三个数每一个都有很多的取值,现在给你一个x让你判断任意的ABC相加是否等于X(有多组值),若等于就YES,否则就NO,一开始我想用四个for循环来写但是后来想了一下觉得太繁琐而且又容易超时,于是找到了二分法来写,简单易懂。
      具体步骤:将前两个数组相加后的值赋给一个新的数组,然后用x的值减去另外一个数组的值,判断两者是否相等。
 
 
 
 
原文地址:https://www.cnblogs.com/lbyj/p/5696900.html