POJ_3258_River Hopscotch_二分搜索

.

题意

一条河里有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 50010
int 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值