POJ_3258_River Hopscotch_二分搜索

来源:互联网 发布:php流量统计源码 编辑:程序博客网 时间:2024/06/05 16:48
.

题意

一条河里有N个石头,另外还有起始位置0和终点L处有石头。用最佳方案移走其中M块石头,使得新的情形下最近的两块石头的距离最大,这个值最大是多少?

IO

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

分析

二分搜索,一开始懒得想了就查题解,结果被题解忽悠的一愣一愣的,然后就彻底糊涂了。
主要难点是如何判断一个值是否合法,以修改二分搜索边界。
定义一个值V合法为:跳V距离,能够掠过的石头的数量小于等于M为合法,此事二分左边界应移动至此,否则二分右边界移动至此。(我的二分设定左右边界为左闭右开区间)

代码

#include<iostream>#include<cstdio>#include<cstring>#include<cmath>#include<algorithm>using namespace std;#define MXN 50010int l,n,m;int a[MXN];bool ok(int val){    int sum=0,cnt=0;    for(int i=1;i<=n+1;++i){        if((sum+=a[i]-a[i-1])<val)            ++cnt;        else    sum=0;    }    return cnt<=m;}int main(){    while(scanf("%d%d%d",&l,&n,&m)!=EOF){        int L=l,R=l;        a[0]=0,a[n+1]=l;        for(int i=1;i<=n;++i)   scanf("%d",a+i);        sort(a,a+n+2);        for(int i=1;i<=n+1;++i) L=min(L,a[i]-a[i-1]);        while(L+1<R){            int M=(L+R)>>1;            if(ok(M))   L=M;            else    R=M;        }        printf("%d\n",L);    }    return 0;}
0 0
原创粉丝点击