题目
描述
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?
输入
-
Line 1: Two space-separated integers: N and C
-
Lines 2…N+1: Line i+1 contains an integer stall location, xi
输出 -
Line 1: One integer: the largest minimum distance
样例输入
5 3
1
2
8
4
9
样例输出
3
提示
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.
思路
牛住牛栏,要求每个牛之间的最短距离最大。牛栏是个点,不是一段距离。
要求的是点和点之间的最短距离的最大值,不是要求每个牛之间的距离都是最短的,只求所有牛之间的距离的最小值。
将最小距离设出来,并带入进行检测判断即可。最小距离的范围是0到N/c,进行二分搜索即可。
#include <stdio.h>
#include <algorithm>
using namespace std;
int main()
{
freopen("1.txt","r",stdin);
int i,n,c,last,next,j;
scanf("%d%d",&n,&c);
int stall[n],b=0,e=n-1,m,D;
for(i=0;i<n;i++){
scanf("%d",&(stall[i]));
}
sort(stall,stall+n);
b = 1;
e = stall[n-1]/c;
while(b<=e){
//m = b+(e-b)/2;
m = (b+e)/2;
last = 0;
next =1;
j = 0; //counter
while(next<n){
if(stall[next]-stall[last]>=m){
last = next ;
j++;
}
next++;
}
if(j >= c-1){ // 必须是大于,不能取等于
b = m+1;
D = m;
}else{
e = m-1;
}
}
printf("%d",e);
return 0;
}