传送门:牛客
题目描述:
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 located at distinct integer positions x1,x2,…,xN on the number line. If a cow is
launched with power R landing at position x, this will causes a blast of "radius R", destroying all hay bales
within the range x−R…x+R.
A total of K cows are available to shoot, each with the same power R. Please determine the minimum
integer value of R such that it is possible to use the K cows to detonate every single hay bale in the scene.
输入:
7 2
20
25
18
8
10
3
1
输出:
5
牛客网上的四星题,实际上难度应该差不多两星??
一道比较单纯的二分答案的题目,直接二分奶牛爆炸的范围即可,至于check函数方面,我们可以枚举每一个需要爆破的草堆的位置,然后在此基础上加上2*mid,将其当做我们的右端点,需要爆破的草堆的位置当做左端点,此时我们判断需要爆破的数量和我们奶牛的数量即可
注意点:注意二分模板的写法即可
具体代码:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <string.h>
#include <stack>
using namespace std;
typedef long long ll;
#define inf 0x3f3f3f3f
#define root 1,n,1
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
inline ll read() {
ll x=0,w=1;char ch=getchar();
for(;ch>'9'||ch<'0';ch=getchar()) if(ch=='-') w=-1;
for(;ch>='0'&&ch<='9';ch=getchar()) x=x*10+ch-'0';
return x*w;
}
#define maxn 1000000
#define ll_maxn 0x3f3f3f3f3f3f3f3f
int N,K;int x[maxn];
int check(int mid) {
int l_pos=-1;int num=K;
for(int i=1;i<=N;i++) {
if(x[i]>l_pos) {
if(num>0) {
l_pos=x[i]+2*mid;
num--;
}
else return false;
}
}
return true;
}
int main() {
N=read();K=read();
for(int i=1;i<=N;i++) {
x[i]=read();
}
sort(x+1,x+N+1);
int l=0,r=x[N];int ans;
while(l<=r) {
int mid=(l+r)>>1;
if(check(mid)) {
ans=mid;
r=mid-1;
}else {
l=mid+1;
}
}
cout<<ans<<endl;
return 0;
}