River Hopscotch
Problem Description
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.
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
Sample Input
25 5 2
2
14
11
21
17
Sample Output
4
Hint
Before removing any rocks, the shortest jump was a jump of 2 from 0 (the start) to 2. After removing the rocks at 2 and 14, the shortest required jump is a jump of 4 (from 17 to 21 or from 21 to 25).
题意:
奶牛每年都会举办一个游戏,在一条笔直的河上跳石头,从位置0跳到L(0和L处都固定有石头),中间还有N个石头,位置分别为Ai,为了加大难度,我们选择移除M个石头,如何选择这些石头,才能使得石头间的最短距离最大?
解题思路:
二分答案。对最短距离进行二分,设为d,用pos记录上一个石头的位置,对石头遍历,如果第i个石头离pos的距离大于等于d,则说明这个石头无需移除,pos=a[i],如果第i个石头离pos的距离小于d,则说明这个石头必须移除,记录好移除石头的个数。遍历结束后,看被移除的石头个数是否小于等于M,如果是,则说明最短距离大于等于d,继续找更大的,如果不是,则找比d小的。
Code:
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
const int maxn=50000+4;
int a[maxn];
int L,N,M;
bool f(int d)
{
int cnt=0,pos=0;
for(int i=0; i<=N;i++)
{
if(a[i]-pos>=d)
{
pos=a[i];
}
else
{
cnt++;
}
}
if(cnt<=M)
return true;
return false;
}
int bs()
{
int lo=1,hi=L;
int ans;
while(lo<=hi)
{
int mid=((hi-lo)>>1)+lo;
if(f(mid))
{
ans=mid;
lo=mid+1;
}
else
hi=mid-1;
}
return ans;
}
int main()
{
while(scanf("%d%d%d",&L,&N,&M)!=EOF)
{
for(int i=0; i<N; i++)
{
scanf("%d",a+i);
}
a[N]=L;
sort(a,a+N+1);
int ans=bs();
cout<<ans<<endl;
}
return 0;
}