Description
Farmer John has built a new long barn, with N (2 <= N <= 100,000) stalls. The stalls are located along a straight line at positions x1,...,xN (0 <= xi <= 1,000,000,000).
His C (2 <= C <= N) cows don't like this barn layout and become aggressive towards each other once put into a stall. To prevent the cows from hurting each other, FJ want to assign the cows to the stalls, such that the minimum distance between any two of them is as large as possible. What is the largest minimum distance?
His C (2 <= C <= N) cows don't like this barn layout and become aggressive towards each other once put into a stall. To prevent the cows from hurting each other, FJ want to assign the cows to the stalls, such that the minimum distance between any two of them is as large as possible. What is the largest minimum distance?
Input
* Line 1: Two space-separated integers: N and C
* Lines 2..N+1: Line i+1 contains an integer stall location, xi
* Lines 2..N+1: Line i+1 contains an integer stall location, xi
Output
* Line 1: One integer: the largest minimum distance
Sample Input
5 3 1 2 8 4 9
Sample Output
3
Hint
OUTPUT DETAILS:
FJ can put his 3 cows in the stalls at positions 1, 4 and 8, resulting in a minimum distance of 3.
Huge input data,scanf is recommended.
FJ can put his 3 cows in the stalls at positions 1, 4 and 8, resulting in a minimum distance of 3.
Huge input data,scanf is recommended.
以样例为例,有5间牛舍,坐标分别为1、2、4、8、9,有3头牛,每间牛舍只能住一头牛,每头牛之间距离保持的越大越好,在满足每头牛之间距离至少为d时所有牛都住得下的情况下,寻找最大的d。
#include<cstdio>
#include<algorithm>
using namespace std;
int stall[100000+5],n,c;
bool check(int d)
{
int cnt=1,ed=1,i;
do{
for(i=ed+1;i<=n;i++){
if(stall[i]-stall[ed] >= d) break; //从当前牛舍的后一个开始遍历牛舍,遇到第一个符合的牛舍跳出
}
if(i<=n) //如果确实找到了那个牛舍
{
cnt++;
ed=i; //更新当前牛舍位置
}
if(cnt>=c) return 1; //如果已经让所有牛可以住下了,就返回true
}while(i<n);
return 0;
}
int main()
{
while(scanf("%d %d",&n,&c)!=EOF)
{
for(int i=1;i<=n;i++) scanf("%d",&stall[i]);
sort(stall+1,stall+n+1);
int st=0,ed=1000000,mid;
while(ed-st>1)
{
int mid=st+(ed-st)/2;
if(check(mid)) st=mid; //如果两头牛间至少保持mid距离的情况下,可以让所有牛都住得下,就去找更大的
else ed=mid; //如果两头牛间至少保持mid距离的情况下,不能让所有牛都住得下,就去找更小的
}
/*
例如当ed-st==2时,mid=st+1,
如果check(mid)==true,st=mid(即st+=1),此时再去判定 ed-st>1 == false,此时st是可以符合的
如果check(mid)==false,ed=mid(即ed-=1),此时再去判定 ed-st>1 == false,此时显然ed和mid都是不符合的,只能选择st
*/
printf("%d\n",st);
}
}