刷题记录:牛客NC24017[USACO 2016 Jan S]Angry Cows

这是一篇关于算法的博客,主要介绍了如何利用二分搜索策略解决一个名为'愤怒的奶牛'的游戏关卡设计问题。游戏中,玩家需要确定奶牛爆炸的最小半径来爆破所有草堆。题目给出一系列草堆位置和可用奶牛数量,要求找到最小的爆炸半径。博主提供了详细的二分搜索算法实现,包括检查函数和代码示例,讨论了问题的难度和解决方案的简洁性。
摘要由CSDN通过智能技术生成

传送门:牛客

题目描述:

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值