您的位置:首页 > 其它

(找数字)HDU - 2141

2017-01-11 00:59 274 查看
HDU - 2141

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.

InputThere 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.
OutputFor 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三个集合,再给出一个数X,判断是否  Ai+Bj+Ck = X;

思路:代码可能很好写,超时才是坑点,看代码;

//注意时间复杂度
#include<stdio.h>
#include<algorithm>
using namespace std;
int d[3000000];//m*n的范围
int main()
{
int a[505],b[505],c[505];
int m,n,k,i,j,t,p,h,w=1,r;
while(scanf("%d %d %d",&m,&n,&k)!=EOF)
{
for(i=0;i<m;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
scanf("%d",&b[i]);
for(i=0;i<k;i++)
scanf("%d",&c[i]);
r=0;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
d[r++]=a[i]+b[j];//算出a[i]和b[j]的和,减少复杂度的关键一步 ,避免后续代码循环
sort(d,d+r);//一次排序代替a,b,c三个数组的排序,避免后续代码循环
scanf("%d",&t);
printf("Case %d:\n",w++);
while(t--)
{
bool flag=true;
scanf("%d",&h);
for(i=0;i<k;i++)//由于上面做出的优化,这里只需要一次循环就可以了
{
int left=0,right=r-1,mid;
while(right>=left)//二分的关键应用
{
mid=(left+right)/2;
if(c[i]+d[mid]==h)//a,b,c三个数组同 h 进行比较
{
flag=false;
break;
}
else if(c[i]+d[mid]>h)
{
right=mid-1;
}
else if(c[i]+d[mid]<h)
{
left=mid+1;
}
}
if(!flag)
break;
}
if(!flag)
printf("YES\n");
else
printf("NO\n");
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: