题目
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
题意
农夫 John 建造了一座很长的畜栏,它包括N (2≤N≤100,000)个隔间,这些小隔间的位置为x0,…,xN-1 (0≤xi≤1,000,000,000,均为整数,各不相同).John的C (2≤C≤N)头牛每头分到一个隔间。牛都希望互相离得远点省得互相打扰。怎样才能使任意两头牛之间的最小距离尽可能的大,这个最大的最小距离是多少呢?
思路
先得到排序后的隔间坐标 x0,…,xN-1 。然后在[L,R]内用二分法尝试“最大最近距离”D = (L+R)/2 。L,R初值为[0, xN-1 - x0]
若D可行,则记住该D,然后在新[L,R]中继续尝试(L= D+1)
若D不可行,则在新[L,R]中继续尝试(R= D-1)
代码
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<string.h>
using namespace std;
const int MAX = 100010;
int a[MAX],n,m;
bool Count(int d)
{
int t = a[0],count = 1;
for(int i = 1;i < n;i ++)
{
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];
while(x <= y)
{
int mid=(x+y)/2;
if(Count(mid))
x=mid + 1;
else
y=mid - 1;
}
return y;
}
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;
}