您的位置:首页 > 其它

HDU 2141 Can you find it?

2016-05-03 10:50 441 查看
Can you find it?

Time Limit: 10000/3000 MS (Java/Others) Memory Limit: 32768/10000 K (Java/Others)

Total Submission(s): 21914 Accepted Submission(s): 5546

Problem 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

题解:将Ai+Bj+ck=s转化为:Ai+Bj=S-ck再利用二分法去查找

二分法:又叫做折半查找,主要的核心是函数Binsrch:(针对的是有序的一组数据进行查找,在进行之前先进行排序(从小到大))

int Binsrch(__int64 k,int low,int high)
{
int mid;
while(low<=high)
{
mid=(low+high)>>1;
if(d[mid]==k)
{
return 1;
break;
}
else if(d[mid]>k)
{
high=mid-1;

}
else if(d[mid]<k)
{
low=mid+1;
}
}
return 0;
}


代码中用到了去重函数unique(针对的是有序的连续的相等的数的去重)

得到的返回值是最后一个数的地址,去重并不是将其删除,而是将其挪到了后面

q=unique(d,d+q)-d;///去重函数unique(有顺序连续相同的去重)


代码:

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <string>

using namespace std;
int a[505],b[505],c[505];
__int64 d[250025];///可能会超过int范围
///二分查找函数
int Binsrch(__int64 k,int low,int high) { int mid; while(low<=high) { mid=(low+high)>>1; if(d[mid]==k) { return 1; break; } else if(d[mid]>k) { high=mid-1; } else if(d[mid]<k) { low=mid+1; } } return 0; }

int main()
{
int ans=0;
int l,n,m;
while(~scanf("%d %d %d",&l,&n,&m))
{
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]);
sort(c,c+m); ///将C按从小到大排列
int q=0;
for(int i=0; i<l; i++)
{
for(int j=0; j<n; j++)
d[q++]=a[i]+b[j];

}
//d[q]='\0';
sort(d,d+q);///将a,b的和存放在d中排序(从小到大)
q=unique(d,d+q)-d;///去重函数unique(有顺序连续相同的去重)
int s,k;
scanf("%d",&s);
printf("Case %d:\n",++ans);
while(s--)
{
scanf("%d",&k);
if(k<c[0]+d[0]||k>c[m-1]+d[q-1]) ///如果超越了最小和最大NO
{
printf("NO\n");
continue;
}

else
{
int t=0;
for(int j=0; j<m; j++)
{
__int64 x=k-c[j];
if(Binsrch(x,0,q))///如果二分找到,则t=1;
{
t=1;
break;
}

}
if(t)
printf("YES\n");
else
printf("NO\n");

}

}

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: