The annual Games in frogs' kingdom started again. The most famous game is the Ironfrog Triathlon. One test in the Ironfrog Triathlon is jumping. This project requires the frog athletes to jump over the river. The width of the river is L (1<= L <= 1000000000). There are n (0<= n <= 500000) stones lined up in a straight line from one side to the other side of the river. The frogs can only jump through the river, but they can land on the stones. If they fall into the river, they
are out. The frogs was asked to jump at most m (1<= m <= n+1) times. Now the frogs want to know if they want to jump across the river, at least what ability should they have. (That is the frog's longest jump distance).
Input
The input contains several cases. The first line of each case contains three positive integer L, n, and m.
Then n lines follow. Each stands for the distance from the starting banks to the nth stone, two stone appear in one place is impossible.
Output
For each case, output a integer standing for the frog's ability at least they should have.
Sample Input
6 1 2
2
25 3 3
11
2
18
Sample Output
4
11

题意:
一条长为l的河中有n块石头,仅可走m次到河对岸,求所有可行方案中最大跳跃距离的最小值。

思路:
先设立距离的最大值,因为每次跳过的石头数量不一样,因此,设定一个边界,初始化为第一块石头的位置,随后跨越多块石头,跨越距离超过设定的最大值,则将边界设为跨越后的前一块石头,并记录跨越次数。若跨越次数超过m次,则返回false。
据上编写函数:

bool solve(ll num) {
    ll k = 0, r = sic[0];
    for (int i = 1; i <= n + 1; i++) {
        if (sic[i] - sic[i - 1] > num)
            return false;
        if (sic[i] - r > num) {
            k++;//记录次数
            r = sic[i - 1];//设立边界
            if (k >= m)
                return false;
        }
    }
    return true;//若不存在超限,返回true
}

因为最大距离我们不知道,所以使用二分法来设立最大距离:

ll serch() {
    ll less = 0, max = l;
    ll ans;
    while (less <= max) {
        ans = (less + max) / 2;
        if (solve(ans))
            max = ans - 1;
        else
            less = ans + 1;
    }
    return less;
}

应注意计算时数据的范围

代码:

#include<iostream>
#include<algorithm>
typedef long long ll;

using namespace std;

ll sic[500010];
ll l;
ll n, m;

bool solve(ll num) {
    ll k = 0, r = sic[0];
    for (int i = 1; i <= n + 1; i++) {
        if (sic[i] - sic[i - 1] > num)
            return false;
        if (sic[i] - r > num) {
            k++;
            r = sic[i - 1];
            if (k >= m)
                return false;
        }
    }
    return true;
}
ll serch() {
    ll less = 0, max = l;
    ll ans;
    while (less <= max) {
        ans = (less + max) / 2;
        if (solve(ans))
            max = ans - 1;
        else
            less = ans + 1;
    }
    return less;
}
int main() {
    while (scanf("%lld%lld%lld", &l, &n, &m) != EOF) {
        sic[0] = 0;
        for (int i = 1; i <= n; i++) {
            scanf("%lld", &sic[i]);
        }
        sort(sic, sic + n + 1);
        sic[n + 1] = l;
        printf("%lld\n", serch());
    }
    return 0;
}