P1824 进击的奶牛 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
题目大意:给出n个牛棚,放m头牛,求若想让相邻的牛不打斗最近的距离最大能为多少?
思路:枚举数据范围(距离dis为1到1e9内的数字),判断相邻牛棚距离为dis时能否放下m 头牛,若能则标记为1,不能则标记为0,利用二分查找该距离dis的最大值
1 2 3 4 5 6 7 8 9 ..............1e9
1 1 1 0 0 0 0 0...................0
#include <bits/stdc++.h>
using namespace std;
int n, c;
const int N = 1e6 + 10;
int num[N];
int Count(int dis) { //计数距离为dis时牛棚能放下多少个牛
int now = num[1];
int cnt = 1;
for (int i = 2; i <= n; i++) {
if (num[i] - now >= dis)
cnt++, now = num[i];
}
return cnt;
}
bool check(int dis) { //判断该距离dis放下牛的个数是否满足条件
return Count(dis) >= c;
}
int binary() { //二分查找符合条件的最大的最近距离
int l = 1, r = 1000000000, mid, ans = -1;
while (l <= r) {
mid = (r + l) / 2;
if (check(mid))
ans = mid, l = mid + 1; //如果mid满足,记录mid的值,然后往更大的数寻找,即左指针右移
else
r = mid - 1;
}
return ans;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n >> c;
for (int i = 1; i <= n; i++)
cin >> num[i];
sort(num + 1, num + n + 1);
cout << binary();
return 0;
}