題意:牛要打架,給出一些房子及他們的位置,問如何放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;
}