HDU 2141 Can you find it?(二分)

来源:互联网 发布:茶叶推广方案 知乎 编辑:程序博客网 时间:2024/06/06 01:54
上题:
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 31 2 31 2 31 2 331410
Sample Output
Case 1:NOYESNO
大致题意:就是给你三个数列,A,B,C 从这三个数列中选取三个数,Ai,Bi,Ci 输入一个数X 使得 Ai+Bi+Ci=X,如果找得到就输出YES,找不到就输出NO,
思路:
起初看到之后 直接三层for循环,果断超时,之后又试了一发大表,交过才发现 “all the integers are 32-integers.”所以开始写二分,最初的二分将a和b的和算出来存到sum数组中,之后从c中二分找到X-sum[i],之后还是交了一发超时。。。二分都超时,心态爆炸了。。之后仔细想了一下,我如果枚举sum数组的话那么枚举的长度最大会是500*500,这么大不超时才怪好吗,那我如果枚举c数组,然后利用二分在sum里面找那就长度就可以大大减少了,于是就这样过了
上代码
#include<stdio.h>#include<algorithm>using namespace std;int a[510],b[510],c[510];int sum[2555555];int check(int len,int target){int head=0,tail=len-1;while(tail>head){//printf("---\n");int mid=(head+tail)/2;if(sum[mid]>target){tail=mid;}else if(sum[mid]<target){head=mid+1;}else if(sum[mid]==target){return 1;}}return 0;}int main(){int l,n,m;int ca=0;while(scanf("%d%d%d",&l,&n,&m)!=EOF){int len=0;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]);for(int i=0;i<l;i++){for(int j=0;j<n;j++){sum[len++]=a[i]+b[j];}}sort(sum,sum+len);sort(c,c+m);int s;int t;int flag;scanf("%d",&s);printf("Case %d:\n",++ca);while(s--){flag=0;int fa;scanf("%d",&fa);for(int i=0;i<l;i++){t=check(len,fa-c[i]);if(t==1){flag=1;printf("YES\n");break;}}if(!flag){printf("NO\n");}}}return 0;}

0 0
原创粉丝点击