参考代码
#include<iostream>
#include<algorithm>
using namespace std;
const int MAXLEN = 1e5 + 10;
int nums[MAXLEN];
long long n, c;
bool check(int x) {int cnt = 1, pre = nums[0];//贪心,第一头牛放在第一个隔间for(int i = 1; i < n; ++i) {if (nums[i] - pre >= x) {//以x为距离进行试探cnt++;pre = nums[i];}}if (cnt >= c)//以x为隔间,足够C头牛使用。则x为可行解return true;elsereturn false;
}
int main() {cin >> n >> c;for (int i = 0; i < n; ++i) {cin >> nums[i];}sort(nums, nums + n);int left = -1, right = nums[n - 1] - nums[0] + 1;while (left + 1 != right) {int mid = left + (right - left) / 2;if (check(mid))left = mid;elseright = mid;}cout << left << endl;return 0;
}
题目链接
P1824 进击的奶牛