您的位置:首页 > 运维架构

POJ_3258_River Hopscotch_二分搜索

2015-04-29 23:16 357 查看
.


题意

一条河里有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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: