標籤:des style blog http color 使用 os io
題目連結: POJ 1328 Radar Installation
Description
Assume the coasting is an infinite straight line. Land is in one side of coasting, sea in the other. Each small island is a point locating in the sea side. And any radar installation, locating on the coasting, can only cover d distance, so an island in the sea can be covered by a radius installation, if the distance between them is at most d.
We use Cartesian coordinate system, defining the coasting is the x-axis. The sea side is above x-axis, and the land side below. Given the position of each island in the sea, and given the distance of the coverage of the radar installation, your task is to write a program to find the minimal number of radar installations to cover all the islands. Note that the position of an island is represented by its x-y coordinates.
Figure A Sample Input of Radar Installations
Input
The input consists of several test cases. The first line of each case contains two integers n (1<=n<=1000) and d, where n is the number of islands in the sea and d is the distance of coverage of the radar installation. This is followed by n lines each containing two integers representing the coordinate of the position of each island. Then a blank line follows to separate the cases.
The input is terminated by a line containing pair of zeros
Output
For each test case output one line consisting of the test case number followed by the minimal number of radar installations needed. "-1" installation means no solution for that case.
Sample Input
3 21 2-3 12 11 20 20 0
Sample Output
Case 1: 2Case 2: 1
Source
Beijing 2002
題意
在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;}