Description:
小明有N个牛棚和C头牛。这些牛都很暴躁,一旦距离很近就会互相殴打。现在给你这N个牛棚的位置,请你找到一个安放牛的方式使得两头牛之间的最小距离最大。
Input:
第一行两个数N和C(2<=N<=100000,2<=C<=N),第二行N个数,分别表示N个牛棚的坐标。
Output:
两头牛之间最小距离的最大值。
Sample Input:
5 3
1 2 8 4 9
Sample Output:
3
Reference Code:
#include <cstdio>
#include <algorithm>
using namespace std;
int x[100000+10];
int n,c;
int check(int d){
int pre=0,count=1;
for (int i=0;i<n;i++){
if (x[i]-x[pre]>=d){
pre=i;
count++;
}
}
if (count<c) return 0;
else return 1;
}
int bsrch(int low,int high){
int mid;
while (low<high){
mid=(low+high)/2;
if (check(mid)) low=mid+1;
else high=mid;
}
return high-1;
}
int main(){
scanf("%d%d",&n,&c);
for (int i=0;i<n;i++) scanf("%d",&x[i]);
sort(x,x+n);
int ans=bsrch(1,x[n-1]-x[0]);
printf("%d\n",ans);
}