![NC24017 [USACO 2016 Jan S]Angry Cows](https://img2022.cnblogs.com/blog/2521724/202208/2521724-20220803102317947-652228589.png)
Bessie the cow has designed what she thinks will be the next big hit video game: "Angry Cows". The premise, which she believes is completely original, is that the player shoots cows with a slingshot into a one-dimensional scene consisting of a set of hay bales located at various points on a number line. Each cow lands with sufficient force to detonate the hay bales in close proximity to her landing site. The goal is to use a set of cows to detonate all the hay bales.
There are N hay bales...
题目
1.题目大意
- 给 k 头牛,目标打掉 n 堆稻草, 每头牛的打击范围为 [x-r,x+r](降落点为 x),求最小的 r
2.题目分析
- 二分即可,注意牛的降落位置可以没有草堆
- 对于 check 函数里的初始条件,我们一定会打到第一捆草,它是第一头牛降落位置的左边界
- 假设左边界位置为 x1,右边界为 x2,牛的降落位置为 x
- 牛的打击范围为 [x-r,x+r],即 x1 = x -r, x2 = x + r
- 推一下得到
x1 + r = x2 -r
- 代码中 left = x1 + r, 所以就有边界条件
x[i]-r>left 判断能否打到右边界附近的点
3.题目代码
#include <bits/stdc++.h>
using namespace std;
int n, k;
int x[50004];
bool check(int r){
int sum = 1;
int left = x[0] + r;
for(int i=1;i<n;i++){
if(x[i]-r>left)
{
sum++;
left = x[i] + r;
}
if(sum>k)
return false;
}
return true;
}
int main() {
cin >> n >> k;
for(int i=0;i<n;i++)
cin >> x[i];
sort(x,x+n);
int l = 0;
int r = x[n-1];
int ans;
while(l<=r){
int mid = (l + r) / 2;
if(check(mid)){
ans = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
cout << ans << endl;
}