二分查找
在之前的查找里面大多都是遍历的查找方式,而在大数组的情况下,遍历查找就显得有些无力。相对来说二分查找是一个比较省力的省时间的一种查找方式。而二分法的前提则需要一个有序的数列。
这是整数查找的普通模板
const int MAXN=10011;
int a[MAXN];
int find(int x){
int left=0,right=n-1;
while(left<=right){
int mid=right+left>>1;
if(a[mid]==x) return 1;
else if(a[mid]<x) left=mid+1;
else right=mid-1;
}
return 0;
}
这是浮点数查找的普通模板
const double eps=1e-6;
bool find(double x);//检查x是否满足条件
double finds(double x){
while(right-left>eps){
double mid=(right+left)/2;
if(find(mid) right=mid;
else left=mid;
}
return left;
}
通常在求最小值中的最大值,直接套用距离进行二分运算。
例如下面这一道题:
Every year the cows hold an event featuring a peculiar version of hopscotch that involves carefully jumping from rock to rock in a river. The excitement takes place on a long, straight river with a rock at the start and another rock at the end, L units away from the start (1 ≤ L ≤ 1,000,000,000). Along the river between the starting and ending rocks, N (0 ≤ N ≤ 50,000) more rocks appear, each at an integral distance Di from the start (0 < Di < L).
To play the game, each cow in turn starts at the starting rock and tries to reach the finish at the ending rock, jumping only from rock to rock. Of course, less agile cows never make it to the final rock, ending up instead in the river.
Farmer John is proud of his cows and watches this event each year. But as time goes by, he tires of watching the timid cows of the other farmers limp across the short distances between rocks placed too closely together. He plans to remove several rocks in order to increase the shortest distance a cow will have to jump to reach the end. He knows he cannot remove the starting and ending rocks, but he calculates that he has enough resources to remove up to M rocks (0 ≤ M ≤ N).
FJ wants to know exactly how much he can increase the shortest distance before he starts removing the rocks. Help Farmer John determine the greatest possible shortest distance a cow has to jump after removing the optimal set of M rocks.
Input
Line 1: Three space-separated integers: L, N, and M
Lines 2…N+1: Each line contains a single integer indicating how far some rock is away from the starting rock. No two rocks share the same position.
Output
Line 1: A single integer that is the maximum of the shortest distance a cow has to jump after removing M rocks
Sample Input
25 5 2
2
14
11
21
17
Sample Output
4
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
const int MAXN=100010;
int a[MAXN],n,m,l;
int find(int x){
int num=1,bb=a[0];
for(int i=1;i<n+2;i++){
if(a[i]-bb>=x){
num++;
bb=a[i];
}
if(num>=n+2-m)return 1;
}
return 0;
}
int main(){
cin>>l>>n>>m;
a[0]=0,a[n+1]=l;
for(int i=1;i<=n;i++)cin>>a[i];
sort(a,a+n+2);
int left=0,right=l+1;
while(right>left){
int mid=(left+right)/2;
if(find(mid)) left=mid+1;
else right=mid;
}
cout<<left-1<<endl;
return 0;
}
当然在二分查找的时候要注意边界的问题
在左闭右闭的时候循环条件取left<=right或left!=right;
在左闭右开的时候循环条件取left<right。
至于mid判断大小以后是否需要加一减一,就要看所取的mid在不在自己想要的区间里。