奥赛一本通 1433 愤怒的牛
1433 愤怒的牛
题目大意
从 $n$ 个坐标中选出 $c$ 个位置,使得任意两个位置之间的最小距离尽可能的大。
知识要点
二分答案、贪心
解题思路
二分枚举这个最小距离,按照从左往右的顺序选择不低于最小距离的位置,检查是否能选出 $c$ 个。
参考代码
#include <bits/stdc++.h>
using namespace std;
int n, c, x[100005];
bool check(int m) {
int i = 0, j;
for(int k = 1; k < c; k++) {
j = i + 1;
while(x[i] + m > x[j]) j++; //寻找下一个位置
if(j == n) return false;
i = j;
}
return true;
}
int main() {
scanf("%d%d", &n, &c);
for(int i = 0; i < n; i++) scanf("%d", &x[i]);
sort(x, x + n);
x[n] = 2e9; //末尾添加一个可选位置避免越界
int l = 0, r = 1e9, m;
while(l < r) {
m = (l + r + 1) / 2;
if(check(m)) l = m;
else r = m - 1;
}
printf("%d\n", l);
return 0;
}

浙公网安备 33010602011771号