高效算法——E - 贪心-- 区间覆盖
生活随笔
收集整理的這篇文章主要介紹了
高效算法——E - 贪心-- 区间覆盖
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
E -?貪心-- 區間覆蓋
題目鏈接:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=85904#problem/E
解題思路:
貪心思想,將問題轉化為區間覆蓋問題,將草地的上邊界作為要覆蓋的區間,計算出每個灑水器覆蓋的區間范圍,不能覆蓋的舍去,然后將灑水器按覆蓋范圍的左邊界升序排列。
要覆蓋的最右邊的點right的初始值為0,遍歷灑水器,找一個能覆蓋住right且覆蓋范圍的右邊界最大的灑水器,然后將該灑水器覆蓋的右邊界作為新的right,重復剛才的過程,直到覆蓋整個草地。
程序代碼:
#include <cstdio> #include <iostream> #include <cstring> #include <cmath> #include <algorithm> using namespace std; #define MAX 10005struct node {double left, right;bool operator <(const node &a) const{return left < a.left;} }p[MAX];int n, num; double l, w;int main() {int i; // freopen("input.txt", "r", stdin);while(scanf("%d %lf %lf", &n, &l, &w) != EOF){num = 0;double po, r;for(i = 0; i < n; ++i){scanf("%lf %lf", &po, &r);if(r <= w/2) continue;double t = sqrt(r*r-w*w/4.0);p[num].left = po-t;p[num++].right = po+t;}sort(p, p+num);double left = 0, right = 0;bool flag = false;int result = 0;i = 0;if(p[0].left <= left){while(i < num){int j = i;while(j < num && left >= p[j].left){if(p[j].right > right)right = p[j].right;++j;}if(j == i) break;result++;left = right;i = j;if(left >= l){flag = true;break;}}}printf("%d\n", flag ? result : -1);}return 0; } View Code?
轉載于:https://www.cnblogs.com/www-cnxcy-com/p/4705875.html
總結
以上是生活随笔為你收集整理的高效算法——E - 贪心-- 区间覆盖的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CentOS 6.5 PYPI本地源制作
- 下一篇: MKNetWorkKit打印URL