C - Radar Installation
题目描述:
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.
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:
Output:
题目大意:
这道题主要讲了在一个笛卡尔坐标系中(直角坐标系)中陆地在x轴下方,海洋在x轴上方,海洋中有许多个岛屿,输入多个岛屿到坐标,然后在陆地上,安置了雷达,题目输入中给出了雷达探测范围,要求用最少的雷达探测多一点岛屿,如果岛屿不在雷达探测范围中,就输出-1,如果都在,要求用最少到雷达,覆盖全部岛屿。
思路分析:
看到这道题第一瞬间人是傻到,完全不知道要如何下手,从一个二维的空间中去解决这道题,一开始想到是求出每个岛屿的范围,然后就不知道了,参考网上大神的做法,这道题运用了贪心算法,并且确实求出每个岛屿在x轴上的范围,然后排序,可以理解为每个岛屿都有一个区间范围,将他们区间分为左端点和右端点,如果一个岛屿的右端点大于另一个岛屿的左端点,说明他们同在一个集合中。依次不断循环下去,找出最优解,输出即可。
代码:
#include<stdio.h>
#include <iostream>
#include <algorithm>
#include <stdlib.h>
#include <math.h>
using namespace std;
struct Num//记录左端点和右端点
{
double Lemonleft;
double LemonRight;
}Num1[1000];
bool cmp(Num a,Num b);
int LemonScanf(int b,int c);
bool cmp(Num a,Num b)//判断sort函数比大还是比小
{
if(a.LemonRight==b.LemonRight)
{
return a.Lemonleft>b.Lemonleft; // r相同 左端点 大到小
}
else
return a.LemonRight<b.LemonRight; //按右端点 小到大
}
int LemonScanf(int b,int c)//输入数据与判断
{
int a,num=0,e,flag=0;
double x1,y1,k;
for(a=0;a<b;a++)
{
scanf("%lf %lf",&x1,&y1);
if(y1>c || c<0)//如果超出雷达范围,就输出-1
{
flag=1;//开关
}
Num1[a].Lemonleft=x1-sqrt(c*c-y1*y1);
Num1[a].LemonRight=sqrt(c*c-y1*y1)+x1;
}
if(flag)
{
return -1;
}
sort(Num1,Num1+b,cmp);//排序端点值
k=Num1[0].LemonRight;
num++;//雷达数
for(e=1;e<b;e++)//贪心开始,比较左右端点
{
if(Num1[e].Lemonleft>k)
{
k=Num1[e].LemonRight;
num++;
}
}
return num;
}
int main()
{
int d,e=1,b,c;
while(scanf("%d %d",&b,&c)!=EOF)
{
if(b==0 && c==0)break;
d=LemonScanf(b,c);
printf("Case %d: %d\n",e++,d);
}
}