HDOJ 2141 Can you find it?(二分搜索的优化+总结)

来源:互联网 发布:php解析json数组 编辑:程序博客网 时间:2024/05/22 02:16

Can you find it?

Time Limit: 10000/3000 MS (Java/Others) Memory Limit: 32768/10000 K (Java/Others)Total Submission(s): 1328 Accepted Submission(s): 429 
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 31 2 31 2 31 2 331410
 
Sample Output
Case 1:NOYESNO
 
Author
wangye
 
Source
HDU 2007-11 Programming Contest
 
Recommend
威士忌

直接用三重循环肯定超时。

只要把里面两重循环替换成二分搜索算法,就可以了。

先将里面两重循环的结果放到一个数组了。

然后把这个数组排序,因为二分查找需要该数组单调。


二分查找总结:

1.注意循环条件,直接循环100次的精度可以达到10的-30次方,如果控制成一定的精度退出循环,精度太小,由于浮点数偏差,可能陷入死循环。

 2.二分查找要注意开区间和闭区间,如果(K】,找到的是第一个等于K的值。如果【K)找到的是最后一个等于K的值
 3.二分适用于单调函数,三分适用于单峰函数


#include<iostream>#include<string>#include<cstring>  #include<cmath>  #include<algorithm>  using namespace std;int l, n, m;int a[510];int b[510];int c[510];int x[1010];int lh[250010];bool cmp(int a, int b){return a < b;}bool binary(int x){for (int i = 0; i < m; i++){int first=0;int last=n*l;if (lh[first] + c[i] == x)return true;   //因为0的时候没有查找过while (first < last - 1){int mid = (first + last) / 2;if (lh[mid] + c[i] == x)return true;if (lh[mid] + c[i] > x)last = mid;else first = mid;}}return false;}int main(){int cnt = 0;while (scanf("%d%d%d",&l,&n,&m)!=EOF){cnt++;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++){lh[i*n + j] = a[i] + b[j];}}sort(lh, lh + n*l, cmp);int s;scanf("%d", &s);for (int i = 0; i < s; i++){scanf("%d", &x[i]);}printf("Case %d:\n", cnt);for (int i = 0; i < s; i++){if(binary(x[i]))printf("YES\n");else{printf("NO\n");}}}return 0;}



原创粉丝点击