您的位置:首页 > 编程语言 > Go语言

【贪心】POJ1328 Radar Installation

2014-04-27 00:46 423 查看

Radar Installation

Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 48887 Accepted: 10916

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

 
 
贪心:
最先的思路,



按岛纵坐标从大到小排序,然后从第一个岛开始,找出两个半径d的圆,让岛恰好在圆上,让后取覆盖点最多的圆,另一个丢弃,标记被覆盖的点,被标记的点便跳过, 直到所有点历遍,圆的个数便是最小雷达数。
这样的方法网上能找到的数据都过了,但就是不能AC。。。。换方法。
 
正确方法:



 
如果B圆的和坐标轴的左交点在A圆右交点的左侧,则B点在A圆内,雷达放在A圆有交点处可覆盖A,B圆,同理判断C圆,雷达放在A圆右交点,可覆盖A,B,C圆。D圆左交点在A圆右交点右侧,所以被覆盖,新加一处雷达。E圆左交点在D圆左交点右侧,右交点在D圆右交点左侧,则取E圆右交点建立雷达可覆盖D,E圆。
按照以上原理,记录每个点圆与坐标轴交叉区域,按左交点位置从小到大排序,再按上面算法贪心。
 
#include<stdio.h>
#include<math.h>
#include<algorithm>
using namespace std;

struct point{
double x,y;
};

struct area{
point left,right;
};

bool cmp(area a,area b){
return a.left.x<b.left.x;
}

int main(){
int count=1;
int i,j;

area radar[1010];
double d;
int n;
int ans;
int flag;
double a,b;
while(scanf("%d %lf",&n,&d)!=EOF){
flag=0;
if(n==0&&d==0)
break;
for(i=0;i<n;++i){
scanf("%lf %lf",&a,&b);
radar[i].left.x=a-sqrt(d*d-b*b);
radar[i].right.x=a+sqrt(d*d-b*b);
if(b<0||b>d||d<=0)flag=1;
}

if(flag){
printf("Case %d: -1\n",count);
count++;
continue;
}

ans=1;
sort(radar,radar+n,cmp);
area temp=radar[0];
for(int i=1;i<n;i++)
{
if(radar[i].left.x>temp.right.x)
{
ans++;
temp=radar[i];
}
else if(radar[i].right.x<temp.right.x)
{
temp=radar[i];
}
}
printf("Case %d: %d\n",count,ans);
count++;
}
return 0;
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  贪心 algorithm