跳石头

跳石头(二分答案)

一年一度的“跳石头”比赛又要开始了!这项比赛将在一条笔直的河道中进行,河道中分布着一些巨大岩石。组委会已经选择好了两块岩石作为比赛起点和终点。在起点和终点之间,有 N 块岩石(不含起点和终 点的岩石)。在比赛过程中,选手们将从起点出发,每一步跳向相邻的岩石,直至到达终点。为了提高比赛难度,组委会计划移走一些岩石,使得选手们在比赛过程中的最短跳跃距离尽可能长。由于预算限制,组委会至多从起点和终点之间移走 M 块岩石(不能移走起点和终点的岩石)。\(,0≤M≤N≤50000,1\le L\le 10000000001≤L≤1000000000\)

直接做很难,所以考虑二分答案。二分最短跳跃距离。对于一个最短跳跃距离,可以贪心的统计出有多少石头需要移走,然后判断石头数量即可。

#include <cstdio>
#include <algorithm>
using namespace std;

const int maxn=5e5+5;
int l, n, m, L, R, stone[maxn];

bool check(int dis){
    int t=0, cnt=0;
    for (int i=1; i<n; ++i){
        t+=stone[i]-stone[i-1];
        if (t<dis) ++cnt; else t=0;
        if (l-stone[i+1]<dis){
            cnt+=n-i-2; break; }
    }
    if (cnt>m) return false;
    else return true;
}

int main(){
    scanf("%d%d%d", &l, &n, &m);
    for (int i=1; i<=n; ++i) scanf("%d", &stone[i]);
    sort(stone+1, stone+n);
    stone[0]=0; stone[++n]=l; ++n;
    L=0, R=l; int mid;
    while (L<R){
        mid=(L+R)>>1;
        if (check(mid)) L=mid+1; else R=mid;
    }
    printf("%d", L-1);
    return 0;
}
posted @ 2017-11-03 14:36  pechpo  阅读(312)  评论(0编辑  收藏  举报