Can you find it? ACM
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
题的大意是有三个数组A B C,每个数组中分别有3,3,3个数,让后每个数组中的数分别为A:1,2,3 B:1,2,3、C:1,2,3。让后现在有S组测试数据。
首先将数据都输入进去,对所输入的数据进行相加再排序,共有A* B* C种情况,让后利用二分法(不懂二分的话,可以看一下我的另一篇讲二分的博客),看所要找的数是否在这些情况中。如果可以找到,输入yes,如果不行,就输出no。
#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
void ff(int *p,int key,int l)
{
int a=0,mid;
mid=l/2;
while(a<l&&p[mid]!=key)
{
if(p[mid]>key)
{
l=mid-1;
}else
{
a=mid+1;
}
mid=(l+a)/2;
}
if(p[mid]==key)
{
printf("YES\n");
}
else
{
printf("NO\n");
}
}
int main()
{
int a,b,c,y=1;
while(~scanf("%d%d%d",&a,&b,&c))
{
int A[510],B[510],C[510];
for(int i=0;i<a;i++)
{
scanf("%d",&A[i]);
}
for(int i=0;i<b;i++)
{
scanf("%d",&B[i]);
}
for(int i=0;i<c;i++)
{
scanf("%d",&C[i]);
}
int d,e=a*b*c,f=0,D[110],E[e];
scanf("%d",&d);
for(int i=0;i<d;i++)
{
scanf("%d",&D[i]);
}
for(int i=0;i<a;i++)
{
for(int j=0;j<b;j++)
{
for(int k=0;k<c;k++)
{
E[f]=A[i]+B[j]+C[k];
f++;
}
}
}
sort(E,E+e);
printf("Case:%d\n",y);
y++;
for(int i=0;i<d;i++)
{
ff(E,D[i],e);
}
}
return 0;
}