poj 1328 Radar Installation(贪心)

如图,x轴表示海岸线,x轴的上方表示海,给出的点表示每一个岛屿,然后要在海岸线上安装一些雷达,每个雷达的覆盖范围都是一个半径为r的圆,需要安装一些雷达使得所有的岛屿都在雷达的覆盖范围内。然后要求使得这个雷达数最小。


这是一个贪心的题,先说说我一开的想法,一开始是先对点按照x轴进行排序,从左到右,先对第一个点上安装一个雷达,然后看后面的点在不在这个雷达的覆盖范围内,如果在的话,继续,不在的话,在当前点安装一个雷达,当然,这种贪心的策略是错误的。很简单,假如前三个点,我在第一个点上安装雷达,第二个点在覆盖范围内而第三个点不在覆盖范围内,这样需要安装两个雷达。但是要是我在第二个点安装一个雷达恰好使得第一个与第三个点都在雷达的覆盖范围内,这样的结果不是比上面的贪心更优吗?所以说上面的说法是错误的。


然后,贪心该怎么来?

换个角度,我以每一个岛屿为圆心,按照雷达的覆盖范围为半径画圆,这个圆会与x轴有两个交点,这个区间就是点x在雷达的范围内的雷达的安装区间。

对于每个点,都有一个这样的区间,然后转化成了一个经典的区间贪心问题。找尽量少的点,使得每个区间内都覆盖的点。ok这样就是正确的了。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<cmath>
using namespace std;

struct Point
{
	double x,y;
	Point(const double& x = 0.0,const double& y = 0.0):x(x),y(y){}
	Point(const Point& res)
	{
		this->x = res.x;
		this->y = res.y;
	}
	bool operator < (const Point& res) const
	{
		if(this->y == res.y)
		{
			return this->x < res.x;
		}
		return this->y < res.y;
	}
};

typedef Point Vector;

Vector operator - (const Point& A, const Point& B)
{
	return Vector(A.x - B.x , A.y - B.y);
}

Vector operator + (const Point& A, const Point& B)
{
	return Vector(A.x + B.x , A.y + B.y);
}

double Dot(Vector A,Vector B)
{
	return A.x * B.x + A.y * B.y;
}

double dis(Vector A)
{
	return Dot(A,A);
}

int n;
double d;
vector<Point>A;
vector<Point>seg;

int main()
{
	#ifdef LOCAL
		freopen("in.txt","r",stdin);
	#endif
	int k = 1;
	while(scanf("%d %lf",&n,&d) && n && d )
	{
		A.clear();
		seg.clear();
		bool flag = false;
		double x,y;
		for(int i = 0 ; i < n ; i++)
		{
            scanf("%lf %lf",&x,&y);
			A.push_back(Point(x,y));
			if(y > d)
			{
				flag = true;
			}
		}
		printf("Case %d: ",k++);
		if(flag)
		{
			printf("-1\n");
		}
		else
		{
			for(int i = 0 ; i < A.size() ; i++)
			{
				double x_ = sqrt(d*d - A[i].y * A[i].y);
				seg.push_back(Point(A[i].x - x_ , A[i].x + x_));
			}
			sort(seg.begin(),seg.end());
			int ans = 0;
			bool vis[1010];
			memset(vis,false,sizeof(vis));
			bool f = false;
			double cnt = 0.0;
			for(int i = 0 ; i < seg.size() ; i++ )
			{
				if(!f)
				{
					cnt = seg[i].y;
					f = true;
					ans++;
				}
				else
				{
					if(cnt >= seg[i].x && cnt <= seg[i].y )
					{
						continue;
					}
					else
					{
						cnt = seg[i].y;
						ans++;
					}
				}
			}
			printf("%d\n",ans);
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值