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 2
1 2
-3 1
2 1
1 2
0 2
0 0
Sample Output
Case 1: 2
Case 2: 1
結題思路
題意要求我們找到能夠掃描到全部海島的最少的燈塔數。
要求1:當能掃描到兩個海島的圓心區域出現交集時,我們可以通過一個燈塔就掃描到這兩個海島;
要點2:當某個海島需要跟前一個海島共用燈塔時,這個海島必須跟前面的合法的交集區出現交集。
當我們首先讀入一個海島,得到這個海島的燈塔圓心區域的右值A;讀入第二個海島,此時,C < A && B < A;這時,如果我們要讀入第三個海島,而這個海島要跟前面的海島共用燈塔,需要第三個海島跟BC出現交集
程序步驟
第一步、讀入數據,首先對不合法的樣例直接輸出非法。
第二步、對合法樣例的燈塔圓心區域的左值進行遞增排序。
第三步、根據區域交集的情況,判斷需要的燈塔個數。
具體程序(AC)如下
#include <iostream>
#include <algorithm>
#include <set>
#include <vector>
#include <cmath>
#include <limits>
using namespace std;
struct node
{
double start;
double end;
// const成員函數不可以修改對象的數據,不管對象是否具有const性質.它在編譯時,以是否修改成員數據爲依據,進行檢查
bool operator < (const node& b) const
{
return start < b.start;
}
};
int main()
{
int n, d;
int x, y;
int result = 0;
double distance;
int index = 0;
while(cin>> n >>d)
{
index++;
result = 0;
if(n == 0 && d == 0)
break;
vector<node> island(n);
for(int i = 0; i < n; ++i)
{
cin>> x >> y;
if(result < 0)//即使出現了非法數據,我們還是需要把樣例全部讀一遍
continue;
if(y > d)//海島位置超過了燈塔的掃描半徑
{
result = -1;
continue;
}
else
{
distance = sqrt(d * d - y * y + 0.0);
island[i].start = x - distance;//燈塔圓心的左值
island[i].end = x + distance;//燈塔圓心的右值
}
}
if(result < 0)
cout<<"Case "<<index<<": "<< -1<<endl;
else
{
sort(island.begin(), island.end());
double end = -numeric_limits<double>::max();
int counter = 0;
for(int i = 0; i < n; ++i)
{
if(island[i].start > end)//需要一個新燈塔
{
counter++;
end = island[i].end;
}
else if(island[i].end < end)//出現交集,且爲內包含
end = island[i].end;
}
cout<<"Case "<<index<<": "<<counter<<endl;
}
}
return 0;
}