标签:des style blog http color 使用 os io
题目链接: POJ 1328 Radar Installation
Description
Input
Output
Sample Input
3 2 1 2 -3 1 2 1 1 2 0 2 0 0
Sample Output
Case 1: 2 Case 2: 1
Source
题意
在x轴表示的海岸线上需要布置雷达,以覆盖海中的n个海岛,雷达的覆盖半径为d,求解如何选择布置点才能使用到的雷达最少。如果有的海岛不能被覆盖到,那么输出-1。
分析
考察以海岛为圆心,做半径为d的圆,看与x轴相交的那段区间,这样的话,这个区间内的任何位置布置雷达,都是可以覆盖这个海岛的,对于所有的海岛,当然不乏求到的区间有部分重合的情况,那么在这个重合的区间中布置雷达,当然就能覆盖到两个以上的点,这样就能节省雷达,雷达所在的区间越多,节省的雷达就越多。
思想
典型的贪心思想。对于求出的每一个区间,我们进行排序,让区间右端点小的排在前面,如果右端点相等,那么左端点大的排在前面(想想为什么)。
那么该如何选择布置点呢?
首先我们选取排序号后的第一个区间的右端点为第一个布置点,它的位置为st,然后再按顺序找后面的区间。如果当前区间的左端点大于st,说明st位置的雷达不能覆盖到这个海岛,那么雷达数加1,同时更新st为这个区间的右端点。如果当前区间的左端点小于等于st,则说明st位置的雷达能覆盖这个海岛,忽略这个区间。
代码
/* POJ_1328_Radar_Installation Author: Sign_ Greedy */ #include <iostream> #include <cstdio> #include <cmath> #include <algorithm> using namespace std; int n, d; struct seg { double l, r; }SEG[1010]; seg pos(int x, int y) { seg s; s.l = x - sqrt(d*d - y*y); s.r = x + sqrt(d*d - y*y); return s; } bool cmp(seg a, seg b) { if(a.r == b.r) return a.l > b.l; return a.r < b.r; } int main() { int x[1010], y[1010], cas = 1; while(scanf("%d%d", &n, &d), n, d) { bool flag = true; for(int i = 0; i < n; i++) { scanf("%d%d", &x[i], &y[i]); if(y[i] > d) flag = false; } if(!flag) { printf("Case %d: -1\n", cas++); continue; } for(int i = 0; i < n; i++) SEG[i] = pos(x[i], y[i]); sort(SEG, SEG+n, cmp); int cnt = 1; double st = SEG[0].r; for(int i = 1; i < n; i++) if(SEG[i].l > st) { st = SEG[i].r; cnt++; } printf("Case %d: %d\n", cas++, cnt); } return 0; }
POJ 1328 Radar Installation 雷达安装 贪心问题求解,布布扣,bubuko.com
POJ 1328 Radar Installation 雷达安装 贪心问题求解
标签:des style blog http color 使用 os io
原文地址:http://blog.csdn.net/u011439796/article/details/38295609