Angry Cows(二分答案——好题!)

中文精简版链接

时间限制: 1 Sec 内存限制: 128 MB
题目描述
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.

Bessie 设计了一款新游戏:Angry Cows。在这个游戏中,玩家发射奶牛,每头奶牛落地时引爆一定范围内的干草。游戏的目标是使用一组奶牛引爆所有干草。

N捆干草排列在数轴上的不同位置。第 i 捆干草的的位置为 xi​。如果一个威力为 R 的奶牛在 x 位置落地,她将引爆 [x−R,x+R]范围内的所有干草。

你现在可以发射 K 头奶牛,每头奶牛的威力都是 R,现在你需要确定 R 的最小值,使得用 K 头奶牛可以引爆所有干草。

输入
The first line of input contains N (1≤N≤50,000) and K (1≤K≤10). The remaining N lines all contain integers x1…xN (each in the range 0…1,000,000,000).
输出
Please output the minimum power R with which each cow must be launched in order to detonate all the hay bales.
样例输入 Copy
7 2
20
25
18
8
10
3
1

样例输出 Copy
5

题目大意:一排n个坐标,有k个炸弹,要求一个最小范围,能够将坐标轴上的所有目标轰炸。

分析:
二分答案:
具有单调性:范围越大,需要的炸弹数目越小;范围越小,需要的炸弹数目越大 因此,我们遍历范围,在保证全部炸掉的情况下,求得需要的最小炸弹数。
如果能够满足条件的最小炸弹数小于等于k,就说明范围大了,要缩;
(因为,既然小于k个都能全炸掉,那k个肯定也能!)

Code:

//http://icpc.upc.edu.cn/problem.php?cid=2787&pid=12 
#include<bits/stdc++.h>
using namespace std;

const int N=50010;
int n,k,a[N];

int check(int mid) //mid为当前遍历的范围 
{
	int cnt=0;
	for(int i=1,j=1;i<=n;i++) //双指针:i在前走,j来保证(j,i)这个范围能被一个炸弹炸到(即:保证a[i]-a[j]<=2*mid) 
	{
		if(a[i]-a[j]>2*mid) cnt++,j=i; //范围mid不能覆盖了,那就加炸弹 
	}
	if(cnt+1<=k) return 1; //cnt+1才是需要的炸弹数 
	return 0;
}

int main(){
	cin>>n>>k;
	for(int i=1;i<=n;i++) cin>>a[i];
	
	sort(a+1,a+n+1); //数列要有序 
	
	int l=0,r=1e9;
	while(l<r) //模板2 
	{
		int mid=l+r>>1;
		if(check(mid)) r=mid; //因为求的是最小范围,尽量往左走 
		else l=mid+1; 
	}
	cout<<l;
	return 0;
}
如果对二分不太熟悉的话,欢迎来访我的另一篇博客,带你学透二分!!

如果哪里有问题或者不懂的地方欢迎留言评论呀!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值