题意
题目抽象一下,就是N个整数的数组,去除其中的M个,使得具有最小间距的相邻两个数间距最大,即这个最小间距有个上界,不会有比其更大的最小值。
题解
确定上下界,二分搜索。
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 50000 + 3;
int L, n, m;
int a[maxn];
int binarySearch(int lower, int upper){
while(lower <= upper){
int mid = lower + ((upper - lower) >> 1);
int s = 0, e = 1, cnt = 0;
// starting from first rock, assuming mid is the minimum interval.
while(e < n){
if(a[e] - a[s] >= mid) s = e, e++;
else e++, cnt++; // remove one rock
}
if(cnt <= m) lower = mid + 1;
else upper = mid - 1;
}
return upper;
}
int main(){
#ifdef EXMY
freopen("data.in", "r", stdin);
#endif // EXMY
while(scanf("%d %d %d", &L, &n, &m) != EOF){
for(int i = 1; i <= n; ++i) scanf("%d", a + i);
a[0] = 0, a[n + 1] = L; // start and end rocks
n += 2;
sort(a, a + n);
int upper = L, lower = L;
// the upper_bound is the maximum interval between any rocks, the lower_bound is the minimum one.
for(int i = 1; i < n; ++i) lower = min(lower, a[i] - a[i - 1]);
printf("%d\n", binarySearch(lower, upper));
}
return 0;
}