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?
Input
* Line 1: Two space-separated integers: N and C
* 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有一个有n间牛棚的小屋,牛棚在一条直线上,坐标为分别为x[i],但是他的c头牛对牛棚不满,因此会经常相互攻击,FJ为了防止牛之间相互攻击,决定把每头牛都放在离其他牛尽可能远的牛棚中,也就是要最大化最近两头牛之间的距离。
思路:#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<string.h>
using namespace std;
const int MAX = 100010;
int a[MAX],n,m;
bool ok(int d)
{
int t = a[0],count = 1;
for(int i = 1;i < n;i ++)//判断d是否满足,若有m个满足间距d的返回true
{
if(a[i] - t >= d)
{
count ++;
t=a[i];
if(count >= m)
return true;
}
}
return false;
}
int solve()//二分查找
{
int x = 0,y = a[n-1] - a[0];//x和y表示d范围的上下界限
while(x <= y)
{
int mid=(x+y)/2;
if(ok(mid))
x=mid + 1;
else
y=mid - 1;
}
return x - 1;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
for(int i = 0;i < n;i ++)
scanf("%d",&a[i]);
sort(a,a+n);
printf("%d\n",solve());
}
return 0;
}