问题描述
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
问题分析
题目大意为在一条宽度为L的河之间有N块石头,第i块石头到河头的距离为Di,求在移除M块石头后两块石头之间的最短距离的最大值为多少。
既然是求最短距离的最大值,那么这个最短距离一定是在河宽之间的,那么我们只需要通过二分查找的方法来找这个最短距离即可,假设我们通过二分查找设最短距离为min时能不能通过移除M块石头来实现,如果能,那么最短距离最大值则为min,如果不能,则通过二分继续改变min的值。
注意
用C编写的代码因为包含排序部分,博主采用的排序方式会导致时间超限,请自行改为更为高效的排序方式,或采用C++的sort函数进行排序。
代码
#include<stdio.h>
#define SAWP(a,b) {int t;t=a;a=b;b=t;}
int main()
{
int l,n,m,a[50020],i,j,left,rigth,min,pre,ans;
scanf("%d %d %d",&l,&n,&m);
for (i=1;i<=n;i++)
scanf("%d",&a[i]);
a[0]=0;a[n+1]=l;
left=0;rigth=l;
for (i=1;i<n;i++)
for (j=i+1;j<=n;j++)
if (a[i]>a[j])
SAWP(a[i],a[j]);
while (rigth-left>1)
{
min=(left+rigth)/2;//二分
pre=0;
ans=0;
for (i=1;i<=n;i++)
{
if (a[i]-pre>=min) //如果距离大于等于最小距离,则不需要移除该石头
pre=a[i];
else //不超过最小距离则移除该石头
ans++;
}
if (ans>m) //如果移除的石头超过m块
rigth=min;
else
left=min;
}
printf("%d\n",left);
return 0;
}