Description Assume thecoasting is an infinite straight line. Land is in one side of coasting, sea inthe other. Each small island is a point locating in the sea side. And any radarinstallation, locating on the coasting, can only cover d distance, so an islandin the sea can be covered by a radius installation, if the distance betweenthem is at most d. We use Cartesian coordinate system, defining the coasting is the x-axis. Thesea side is above x-axis, and the land side below. Given the position of eachisland in the sea, and given the distance of the coverage of the radarinstallation, your task is to write a program to find the minimal number ofradar installations to cover all the islands. Note that the position of anisland is represented by its x-y coordinates.
![](https://img-blog.csdn.net/20131103223057234?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMjI0OTI0OA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
Input
The input consistsof 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 isthe distance of coverage of the radar installation. This is followed by n lineseach containing two integers representing the coordinate of the position ofeach 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 caseoutput one line consisting of the test case number followed by the minimalnumber of radar installations needed. "-1" installation means nosolution 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
题目大意:海岸为x轴,海岸的一边有若干个小岛,问在x轴上至少建立多少个雷达站,可以把小岛都覆盖。
输入第一行为n和d,n是小岛的数量,d是雷达的辐射半径。接下来n行是n个小岛的坐标,输入为0 0是终止。
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
struct land
{
double x,y;
double l_range,r_range;
}s[1001];
int cmp(const void *a,const void *b);
int main()
{
int n,d,i,cas=0,cnt;
double temp;
while(cin>>n>>d&&(n+d!=0))
{
bool istrue=true;
cnt=1;
for(i=0;i<n;i++)//输入岛屿坐标
{
cin>>s[i].x>>s[i].y;
if(s[i].y>d)
istrue=false;
}
if(!istrue)
cout<<"Case "<<++cas<<": -1"<<endl;
else{
//把结构体按照x坐标由小到大排序
qsort(s,n,sizeof(s[0]),cmp);
//计算l_range,r_range
for(i=0;i<n;i++)//计算每个岛屿,雷达位于x轴的那个范围可以覆盖到
{
s[i].l_range=s[i].x-sqrt((d*d-s[i].y*s[i].y)*1.0);
s[i].r_range=s[i].x+sqrt((d*d-s[i].y*s[i].y)*1.0);
}
//运用了贪心的思想
temp=s[0].r_range;
for(i=1;i<n;i++)
{
if(s[i].l_range>temp)//如果右边岛屿左限大于左边岛屿右限,那么必须增加一个雷达站
{
cnt++;
temp=s[i].r_range;
}
else if(s[i].r_range<temp)//这个类似于右边的岛屿构成的三角形比较瘦高,导致右边的右限小于左边的左限
temp=s[i].r_range;
}
cout<<"Case "<<++cas<<": "<<cnt<<endl;
}
}
return 0;
}
int cmp(const void* a,const void*b)
{
return (*(land*)a).x>(*(land*)b).x?1:-1;
}
总结:这道题花了3个多小时。但是有收获。
1.结构体排序,选修课上刚刚讲过。
2.sqrt(double)传int提交的话会出错
3.贪心思想,不断比较,赋值,比较。。。