Watering Grass(贪心 区间覆盖)

该博客讨论了一种贪心策略在解决区间覆盖问题上的应用。给定一定数量的圆,每个圆的中心位于一条水平草地上,并具有特定半径,目标是最小化开启的圆数以覆盖整个草地。博客内容包括输入输出格式、问题描述、解题思路和AC代码,重点在于如何通过计算每个圆的覆盖区间,然后进行排序和覆盖判断,来确定最小的圆数。当无法完全覆盖草地时,输出-1。
摘要由CSDN通过智能技术生成

Watering Grass(贪心 区间覆盖)

n sprinklers are installed in a horizontal strip of grass l meters long and w meters wide. Each sprinkler is installed at the horizontal center line of the strip. For each sprinkler we are given its position as the distance from the left end of the center line and its radius of operation.
What is the minimum number of sprinklers to turn on in order to water the entire strip of grass?

在这里插入图片描述

Input
Input consists of a number of cases. The first line for each case contains integer numbers n, l and w with n <= 10000. The next n lines contain two integers giving the position of a sprinkler and its radius of operation. (The picture above illustrates the first case from the sample input.)

Output
For each test case output the minimum number of sprinklers needed to water the entire strip of grass. If it is impossible to water the entire strip output -1.

题意: 给出多个圆心和半径,问最少需要多少个圆,才能把花带覆盖完全,如果不能完全覆盖,输出-1

思路: 将草地的上边界作为要覆盖的区间,计算出每个洒水器覆盖的区间范围,不能覆盖的舍去,然后将洒水器按覆盖范围的左边界升序排列,查找,第一个是必用的,然后找左边界尽可能大且小于上一个右边界的,右边界尽可能的大,更新重复即可

AC代码:

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
struct pp
{
	double a,b;
}p[11000];
bool cmp(pp x,pp y)
{
	if(x.a!=y.a)
	return x.a<y.a;
	return x.b>y.b;
}
int main()
{
	int n,i,j;
	double l,w,aa,bb;
	while(~scanf("%d%lf%lf",&n,&l,&w))
	{
		int k=0;
		double maxx=-1;
		for(i=0;i<n;i++)
		{
			scanf("%lf%lf",&aa,&bb);
			if(bb*2<=w)
			continue;
			else
			{
				p[k].a=aa-sqrt(bb*bb-w*w/4.0);
				p[k].b=aa+sqrt(bb*bb-w*w/4.0);//计算覆盖区间
				if(p[k].b>maxx)//找最大右边界
				maxx=p[k].b;
				k++;
			}
		}//printf("%lf--\n",maxx);
		sort(p,p+k,cmp);
	//	for(i=0;i<k;i++)
	//	printf("%lf %lf++\n",p[i].a,p[i].b);
		int f=0;
		if(p[0].a>0||maxx<l)//边界
		{
			printf("-1\n");
			continue;
		}
		double x=0;
		int sum=0;
		while(x<l)
		{
			double y=x;
			for(i=0;i<k;i++)
			{
				if(p[i].b>x&&p[i].a<=y)//注意x,y
				x=p[i].b;
			}
			if(y==x&&y<l)
			{
				f=1;
				break;
			}
			sum++;
		}
		if(!f)
		printf("%d\n",sum);
		else
		printf("-1\n");
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值