hdu 2141 Can you find it?(二分查找变例)

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
 

 初看很简单就是判断三个数加起来的和,但是三个for循环速度还是很慢的,所以细想要用到二分查找。

把函数改为:A+B=X-C,然后二分搜一下就可以了。

完全用的是二分查找的模板。

 1 #include <stdio.h>
 2 #include <math.h>
 3 #include <queue>
 4 #include <vector>
 5 #include <stack>
 6 #include <map>
 7 #include <string>
 8 #include <string.h>
 9 #include <algorithm>
10 #include <iostream>
11 using namespace std;
12 #define K 505
13 int LN[K*K];
14 int binarysearch(int a[],int l,int r,int k){
15     int mid;
16     while(r-l>1){
17         mid=(r+l)/2;
18         if(a[mid]<=k)
19             l=mid;
20         else
21             r=mid;
22     }
23     if(a[l]==k)
24         return 1;
25     else
26         return 0;
27 }//二分查找
28 int main()
29 {
30     int i,j,count=1,q;
31     int L[K],N[K],M[K],s,n,m,l;
32     while(~scanf("%d%d%d",&l,&n,&m)){
33         int h=0;
34         for(i=0;i<l;i++)
35             scanf("%d",&L[i]);
36         for(i=0;i<n;i++)
37             scanf("%d",&N[i]);
38         for(i=0;i<m;i++)
39             scanf("%d",&M[i]);
40         for(i=0;i<l;i++)
41           for(j=0;j<n;j++)
42              LN[h++]=L[i]+N[j];
43          sort(LN,LN+h);
44          scanf("%d",&s);
45          printf("Case %d:\n",count++);
46         for(i=0;i<s;i++)
47         {
48             scanf("%d",&q);
49             int p=0; 
50             for(j=0;j<m;j++)
51             {
52                 int a=q-M[j]; 
53                 if(binarysearch(LN,0,h,a)) 
54                 {
55                     printf("YES\n");
56                     p=1;
57                     break;
58                 }
59             }
60             if(!p) 
61               printf("NO\n");
62         }
63     }
64     return 0;
65 }

 

转载于:https://www.cnblogs.com/wangmengmeng/p/4711361.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值