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

来源:互联网 发布:淘宝女装6皇冠 编辑:程序博客网 时间:2024/05/19 01:28
题目大意:
在一个长为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
原创粉丝点击