题意:牛要打架,给出一些房子及他们的位置,问如何放c头牛使得他们之间的最短距离最大。
利用二分法选择最短相距的距离,慢慢逼近最大值。
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 100000 + 5;
int pos[maxn], n, c;
bool putcows(int space)
{
int cnt = 1;
int last = pos[0];
for(int i = 1; i < n; i++)
{
if(pos[i] - last >= space) {cnt++; last = pos[i];}
if(cnt == c) return true;
}
return false;
}
int main()
{
while(scanf("%d%d", &n, &c) == 2)
{
for(int i = 0; i < n; i++)
scanf("%d", &pos[i]);
sort(pos, pos + n);
int L = 0, R = pos[n - 1] - pos[0] + 1;
while(R - L > 1)
{
int mid = (R + L) / 2;
if(putcows(mid)) L = mid;
else R = mid;//R是非法值
}
printf("%d\n", L);
}
return 0;
}