贪心算法:POJ1328 雷达安装

Description
假定海岸线是一条无限长的直线,陆地在海岸线的一边,海洋在另一边。每个小岛是海洋这边中的一个点,任何一部安在海岸线上的雷达站仅能覆盖距离d,如果一个小岛与雷达站的距离不超过d,那么这个小岛就可被这部雷达站覆盖。 用笛卡尔坐标系,将海岸线作为x轴,海洋位于x轴的上方,陆地在x轴的下方。给出海洋中每个小岛的位置,以及每部雷达站的覆盖距离,写一个程序来找到所需安装的雷达站的最小数,以覆盖所有小岛。注意每个岛屿的位置用x-y坐标表示。
Input
输入由几个测试用例组成。每个测试用例的第一行是两个整数n,d,其中(1<=n<=1000),n是海洋中小岛的个数,d是雷达站的覆盖距离。接下来的n行中,每行表示一个小岛的位置,是一对x,y坐标。每两个测试用例的数据间用一空行隔开。
输入最后以两个0结束。
Output
对于每个测试用例,输出其编号和所需安装的雷达站的最小数目。如果无解,那么就输出-1.
Sample Input
3 2
1 2
-3 1
2 1
1 2
0 2
0 0
Sample Output
Case 1: 2
Case 2: 1

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<math.h>
using namespace std;

struct interval{
	double left;
	double right;
};
const int Max = 1000 + 10;
bool cmp(interval x, interval y){
	return x.left < y.left;
};

int main(){
	int n, d, casenum = 0;
	while(cin >> n >> d){
		if( n == 0 && d == 0)
			break;
		interval a[Max];
		bool flag = true;
		int x, y;
		for(int i = 0; i < n; i++){
			cin >> x >> y;
			if(y > d)
				flag = false;
			else{
				a[i].left = x - sqrt(1.0 * d * d - 1.0 * y * y);
				a[i].right = x + sqrt(1.0 * d * d - 1.0 * y * y);
			}
		}
		sort(a, a + n, cmp);
		/*for(int i = 0; i < n; i++){
			cout << "left="<<a[i].left <<"    right="<<a[i].right<<endl;
		}*/
		if(flag == false){
			cout << "Case "<< ++casenum   <<": -1" << endl;
			continue;
		}
		double current = a[0].right;
		int num = 1;
		for(int i = 0; i < n; i++){
			if(current >= a[i].left){	//如果两个范围重叠,则取更小的范围
				//cout <<current<<" >= " <<a[i].right<< "   缩小,num=" << num<<endl;
				current = min(a[i].right, current);
			}else{		//否则重新安一个雷达
				//cout <<current<<" < " <<a[i].right<< "重装,num=" << num<<endl;
				current = a[i].right;
				num++;
			}
		}
		cout << "Case " << ++casenum  << ": " << num << endl;
	}
	//system("pause");
	return 0;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值