农夫约翰搭了有N (2 <= N <= 100,000) 间牛舍的小屋。牛舍排在一条直线上,第i号牛舍在xi(0 <= xi <= 1,000,000,000)的位置。但是他的M头牛对小屋很不满意,因此相互攻击。约翰为了防止牛之间互相伤害,决定每头牛尽可能放在离其他牛更远的牛舍。也就是最大化两头牛之间的距离
题目分析:贪心,二分答案
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
#define ll long long
vector<ll>b;
int n, c;
bool enough(int inter, vector<ll>b) {
int len = b.size();
int idx = 0, cnt = 1,temp=idx;
while (idx < len) {
while (b[idx] - b[temp] < inter) {
++idx;
if (idx == len)
break;
}
if (idx < len) {
++cnt;
temp = idx;
}
}
return cnt >= c;
}
int main() {
cin >> n >> c;
for (int i = 0; i < n; ++i) {
ll x;
cin >> x;
b.push_back(x);
}
sort(b.begin(), b.end());
ll left = 1, right = b[b.size() - 1] - b[0];
while (left < right) {
ll mid = (left + right + 1) / 2;
if (enough(mid, b)) {
left = mid;
}
else {
right = mid-1;
}
}
cout << left << endl;
}