题目描述:
Every year the cows hold an event featuring a peculiar version of hopscotch that involves carefully jumping from rock to rock in a river. The excitement takes place on a long, straight river with a rock at the start and another rock at the end, L units away from the start (1 ≤ L ≤ 1,000,000,000). Along the river between the starting and ending rocks, N (0 ≤ N ≤ 50,000) more rocks appear, each at an integral distance Di from the start (0 < Di < L).
To play the game, each cow in turn starts at the starting rock and tries to reach the finish at the ending rock, jumping only from rock to rock. Of course, less agile cows never make it to the final rock, ending up instead in the river.
Farmer John is proud of his cows and watches this event each year. But as time goes by, he tires of watching the timid cows of the other farmers limp across the short distances between rocks placed too closely together. He plans to remove several rocks in order to increase the shortest distance a cow will have to jump to reach the end. He knows he cannot remove the starting and ending rocks, but he calculates that he has enough resources to remove up to M rocks (0 ≤ M ≤ N).
FJ wants to know exactly how much he can increase the shortest distance *before* he starts removing the rocks. Help Farmer John determine the greatest possible shortest distance a cow has to jump after removing the optimal set of M rocks.
输入:
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.
输出:
Line 1: A single integer that is the maximum of the shortest distance a cow has to jump after removing M rocks
输入样例:
25 5 2 2 14 11 21 17
输出样例:
4
解题思路:
要找出所有去掉m个石块后,所有中情况的最小边中的最大值,可以使用二分法穷举,找到答案。
解题步骤:
1、建立距离数组,其中源点的距离是0,终点的距离是L,再输入所有石块的距离,对数组从小到大排序后,就得到的原来所有石块的位置;
2、需要的是最大值,所以在二分法中的判定条件成功后需要向上靠拢;
3、判断函数:需要安排n-m个石块,而且紧邻的两个石块之间的距离必须不小于mid,若能安排下,成功,反之失败。
代码实现:
#include <bits/stdc++.h>
using namespace std;
#define maxn 50050
#define maxl 1000000100
int L, m, n;
int arr[maxn];
bool Judge(int x)
{
int num = n - m; //需要安排的石头总数
int pre_vex = 0;
for (int i = 1; i <= num; i++)
{
int next_vex = pre_vex + 1;
while (arr[next_vex] - arr[pre_vex] < x && next_vex <= n) //只有>=0距离的结点可以安排
{
next_vex++;
}
if (next_vex > n)
{
return false;
}
pre_vex = next_vex;
}
return true;
}
int main()
{
cin >> L >> n >> m;
arr[0] = 0;
arr[n + 1] = L;
for (int i = 1; i <= n; i++)
{
cin >> arr[i];
}
sort(arr, arr + n + 2);
int low = 0, high = L;
int ans = 0;
while (high >= low)
{
int mid = (high + low) / 2;
if (Judge(mid))
{
ans = low;
low = mid + 1;
}
else
{
high = mid - 1;
}
}
cout << ans << endl;
return 0;
}