poj 1328 - Radar Installation

本文介绍了一个经典的贪心算法问题——POJ1328雷达安装问题的解决方案。通过计算每个坐标的雷达覆盖范围并进行排序,利用贪心策略确定最少雷达数量以覆盖所有坐标。

                                                                

            这道题还是有点意思的,关键在把问题进行转换,说实话使用贪心解决这道题还真不是我想出来的,关键就在想到要求出每个坐标下,雷达所设的最大左和最右位置,然后再进行贪心选择。

     思路:求出每个坐标下的雷达的最左和最右区间,对其进行非降序排序,选取第一个区间的的右边CurrentRight作为预设的第一个雷达位置,倘若下一个区间和当前有交集,则雷达可设置在交集内,此时更新CurrentRight;如果没有交集则说明需要新加一个雷达。


/*----------------------------------------------------------------------------------------
	* FileName:POJ1328.c
	* author:doodlesomething@163.com
	* date:10-29-2014
	* version:1.0
	* description:Radar Installation  POJ1328 soloved by Greedy Algorithm
-----------------------------------------------------------------------------------------*/



#include <stdio.h>
#include <math.h>


#define N 10

typedef struct {
	double left; 
	double right;
}Pos;

//这样设置是为了理解上的方便
typedef struct {
	int x;
	int y;
}Posi;



/*
* @description:quick sort by the left asc
*/
void QuickSort(Pos P[],int low,int high) {
	int first,last;
	Pos temp;

	if(low >= high) {
		return;
	}

	first = low;
	last = high;
	temp = P[0];

	while(first < last) {
		while(first < last && temp.left <= P[last].left)
			last--;
		P[first] = P[last];

		while(first < last && temp.left >= P[first].left)
			first++;
		P[last] = P[first];
	}

	P[first] = temp;

	QuickSort(P,low,first - 1);
	QuickSort(P,first + 1,high);

}


int main() {
	
	int n,dis,i,flag,total;
	double CurrentRight;
	Pos P[1000];
	Posi S[1000];

	flag = 1;
	total = 1;

	printf("please enter n and dis:");
	scanf("%d,%d",&n,&dis);
	printf("please enter each value:\n");
	for(i = 0; i < n; i++) {
		scanf("%d%d",&S[i].x,&S[i].y);
		if(S[i].y > dis)
			flag = 0;
	}


	if(!flag) {
		printf("result:-1\n");
	}
	else {
		for(i = 0; i < n ; i++) {
			P[i].left =  S[i].x - sqrt( (double) (dis * dis - S[i].y * S[i].y)); 
			P[i].right = S[i].x + sqrt( (double) (dis * dis - S[i].y * S[i].y));
		}

		//QuickSort
		QuickSort(P,0,n - 1);

		CurrentRight = P[0].right;

		for( i = 1; i < n; i ++) {
			if(P[i].left > CurrentRight) {
				total++;
				CurrentRight = P[i].right;
			}
			else {
				CurrentRight = P[i].right >  CurrentRight ? CurrentRight : P[i].right;
			}
		}
		//output
		printf("%d\n",total);
	}


	return 0;
}


/*
Sample Input

3,2
1 2
-3 1
2 1

Sample Output
total:2



Sample Input
1,2
0 2

Sample Output
total:1

*/



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值