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
解题思路:本题归类为贪心算法。从小岛的角度出发,找到当前第i座小岛的雷达应当建立在海岸线x轴上的坐标范围(作为一段线段)。将所有的小岛对应的线段存储在一个数组中,按照左端点坐标排序,挨个查看,
情形1:如果当前线段的左端点在前面一个线段的右端点之前,说明可以将雷达建立在当前线段左端点有前面一个线段的右端点之前,这样一个雷达既可以将前面的小岛覆盖,也可以覆盖当前小岛。(这种情形要分为两种:当前线段右端点在前一个线段右端点的前或者后)
情形2:如果当前线段的左端点在前面一个线段的右端点之后,说明当前线段只能另建一个雷达。
特殊情况:如果有一个小岛离海岸线的最短距离超过了 雷达辐射半径,输出-1。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <math.h>
using namespace std;
struct Node{
double
left,right;//线段左右端点
};
Node node[1010];
bool cmp(Node n1,Node n2){
return
n1.left<n2.left;
}
int n,d;//小岛数量和雷达半径
int solve(){
//先对线段数组排序
sort(node,node+n,cmp);
int sum =1;
double
nowright=node[0].right;
/*
情形1:如果当前线段的左端点在前面一个线段的右端点之前,
说明可以将雷达建立在当前线段左端点有前面一个线段的右端点之前,这样一个雷达既可以将前面的小岛覆盖,也可以覆盖当前小岛。
情形2:如果当前线段的左端点在前面一个线段的右端点之后,
说明当前线段只能另建一个雷达。
*/
for(int i=1;i<n;i++)
{
if(node[i].left<=nowright)
nowright=min(nowright,node[i].right);
else
{
sum++;
nowright=node[i].right;
}
}
return sum;
}
int main(){
int
ncases=1,flag;
while(true)
{
flag=0;
scanf("%d
%d",&n,&d);
if(n==0&&d==0)
break;
int x,y;//小岛坐标
for(int
i=0;i<n;i++)
{
scanf("%d
%d",&x,&y);
if(y>d)
flag=1;
double
temp= sqrt(pow(d,2)-pow(y,2));
node[i].left=x-temp;
node[i].right=x+temp;
}
if(flag==1)
printf("Case
%d: -1\n",ncases++);//无解
else
printf("Case
%d: %d\n",ncases++,solve());
}
return 0;
}