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’.


Sample Input
8 20 2
5 3
4 1
1 2
7 2
10 2
13 3
16 2
19 4
3 10 1
3 5
9 3
6 1
3 10 1
5 3
1 1
9 1
Sample Output
6
2
-1

思路:

贪心与动态规划。

首先是确定什么样的sprinklers符合题意。下面是我在网上找到的一张图。

大致需要判断的有以下三个方面:

  1. 起始位置是否小于0;
  2. 中间是否存在空隙;
  3. 最终位置是否超过l。

中间是需要寻找最优解的(最少),所以用last标记(写的时候没有考虑到)。

#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
typedef double D;
const int N=1e4+5;
int n;
D l,w;
struct node
{
	D left,right;
}a[N];
D gougu(D r)
{
	return sqrt(r*r-(w/2)*(w/2));
}
bool cmp(node x,node y)
{
	return x.left <y.left ;
}
int main()
{
	while(scanf("%d %lf %lf",&n,&l,&w)!=EOF)
	{
		D o,r;
		for(int i=1;i<=n;i++)
		{
			scanf("%lf %lf",&o,&r);
			if(r<w/2)
			{
				a[i].left =a[i].right =0;
			}
			else
			{
				a[i].left =o-gougu(r);
				a[i].right =o+gougu(r);	
			}
		}
		sort(a+1,a+n+1,cmp);
	//	for(int i=1;i<=n;i++)
	//		printf("%lf %lf\n",a[i].left ,a[i].right );
		D st=0,ed=0;
		int last=0,ans=0;
		while(ed<l&&last<=n)
		{
			for(int i=last+1;i<=n;i++)//找到下一个的最优解,即右端最大处 
			{
				if(a[i].left <=st)
				{
					if(a[i].right >ed)
					{
						last=i;
						ed=a[i].right ;
					}
				}
				else
					break;
			}
			if(st==ed)//下一个没找到 
			{
				ans=-1;
				break;
			}
			st=ed;
			ans++;
		//	printf("ans=%d last=%d\n",ans,last);
		}
		if(last>n)
			printf("-1\n");
		else
			printf("%d\n",ans);
	}
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TherAndI

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值