题目链接
思路
$$ 假设一个可行接然后验证 $$
时间复杂度
$$ O(Nlog(max(x_i))) $$
代码
#include <cstdio>
#include <algorithm>
using namespace std;
const int MAXN = 1e5 + 10;
int n, c;
int a[MAXN];
bool check(int mid) {
int cur = a[1];
int cnt = 1;
for (int i = 2; i <= n; i++) {
if (a[i] - cur >= mid) {
cur = a[i];
cnt++;
}
}
return cnt >= c;
}
int main() {
scanf("%d%d", &n, &c);// don't forget &
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);// don't forget &
}
sort(a + 1, a + 1 + n);
int l = 1, r = 1e9, ans = 0;
while (l <= r) {
int mid = (l + r) >> 1;
if (check(mid)) {
ans = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
printf("%d\n", ans);
return 0;
}