UVa 10382 - Watering Grass(贪心+区间覆盖问题)

题目大意:
在一个长为l,宽为w的草坪上,有n个洒水器,现在题目告诉你每个洒水器的位置p和洒水的半径r。问你能否用最少的洒水器覆盖整个草坪。
如果可以输出最少洒水器的个数,如果不能输出-1。
解析:
将洒水器转换为一个矩形的区间,让后用区间覆盖问题求解。



总结:这题超时了好几次,看来题解才水过的,可能是区间覆盖写得有问题。

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int N = 10010;
struct Segment {
	double l,r;
}s[N];
int n;
double l,w;
bool cmp(Segment a,Segment b) {
	return a.l < b.l;
}
int main() {
	while(scanf("%d%lf%lf",&n,&l,&w) != EOF) {
		int tot = 0;
		double dis,p,r;
		for(int i = 0; i < n; i++) {
			scanf("%lf%lf",&p,&r);
			if(r > w/2) {
				dis = sqrt(r*r - (w*w)/4);
				s[tot].l = p - dis;
				s[tot].r = p + dis;
				tot++;
			}
		}
		sort(s,s+tot,cmp);
		bool flag = false;
		if(s[0].l > 0) {
			printf("-1\n");
		}else {
			int cnt,pos;
			double left,max;
			cnt = 0;
			left = max = 0;
			int i = 0;
			while(i < tot) {
				int j = i;
				while(j < tot && s[j].l <= left) {
					if(s[j].r > max) {
						max = s[j].r;
					}
					j++;
				}
				if(i == j) {
					break;
				}
				cnt++;
				left = max;
				i = j;
				if(left >= l) {
					flag = true;
					break;
				}
			}
			if(flag) {
				printf("%d\n",cnt);
			}else {
				printf("-1\n");
			}
		}
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值