POJ 3258 River Hopscotch 二分

二分跳石头的最小距离,对于每一个mid,在judge函数里从0开始不断找下一个石头+mid的位置,如果位置不是对岸,那么count++,最终判断count是否大于等于n-m,同时注意跳到的最后一个位置要<=l,可以用无穷大来处理边界情况。

#include 
#include 
using namespace std;
typedef long long ll;
ll arr[50007], l, inf = 0x3f3f3f3f3f3f3f3f;
int n, m;
void input()
{
    scanf("%lld%d%d", &l, &n, &m);
    for (int i = 0; i < n; i++)
    {
        scanf("%lld", &arr[i]);
    }
    sort(arr, arr + n);
    arr[n] = l;
    arr[n + 1] = inf;
}
bool judge(ll mid)
{
    int next = 0;
    int count = 0;
    int nextval = 0;
    while (next < n)
    {
        next = lower_bound(arr, arr + n + 2, nextval + mid) - arr;
        if (next < n)
        {
            count++;
            nextval = arr[next];
        }
    }
    return count >= (n - m) && next != n + 1;
}
void binarySearch()
{
    ll left = 0, right = l + 1;
    while (left + 1 < right)
    {
        ll mid = (left + right) / 2;
        if (judge(mid))
        {
            left = mid;
        }
        else
        {
            right = mid;
        }
    }
    printf("%lld\n", left);
}
int main()
{
    input();
    binarySearch();
    return 0;
}

你可能感兴趣的:(算法,数据结构)