您的位置:首页 > 其它

A - Can you find it?

2016-07-21 19:35 387 查看
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

求三个数表中是否有满足和为X的三个数,先求前两个数表的和并排序,再枚举第三个数表的数字,用二分搜索法查找和数组里面是否有满足条件的数字,不需要查重。

#include <iostream>
#include <algorithm>
using namespace std;
#define MAXN 505

int a[MAXN];
int b[MAXN];
int c[MAXN];
int d[MAXN * MAXN];

int bs(int key, int num)
{
int lo=0,hi=num;
int mi;
while(lo<=hi)
{
mi=((hi-lo)>>1)+lo;//lo和hi比较大的时候相加可能爆int
if(d[mi]==key) return mi;
else if(d[mi]<key) lo=mi+1;
else hi=mi-1;
}
return -1;//未找到
}

int main()
{
int t = 1;
int l,n,m;
int s,key;
int i,j;
int isYes = 0;
while(cin >> l >> n >> m)
{
for(i = 0; i < l; i++)
cin >> a[i];
for(i = 0; i < n; i++)
cin >> b[i];
for(i = 0; i < m; i++)
cin >> c[i];
cin >> s;
for(int i = 0; i < l; i++)
for(int j = 0; j < n; j++)
d[i*n+j] = a[i] + b[j];
sort(d, d+l*n);
cout << "Case " << t << ":" << endl;
t++;
while(s--)
{
cin >> key;
for(i = 0; i < m; i++)
{
if(bs(key - c[i], l * n) != -1)
{
isYes = 1;
cout << "YES" << endl;
break;
}
}
if(isYes != 1)
cout << "NO" << endl;
isYes = 0;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二分搜索