《算法竞赛进阶指南》贪心篇 雷达设备

雷达设备

题目链接:链接

题目大意:

二维平面上,给出一系列的点,然后在x轴上找到k个点,以他们为圆心,d为半径,形成的这些圆能

否包含所有的点,如果可以的话,找出最小的k值。

思路:

把给出的点转化为区间,然后就是求用最少的点包含于所有的区间

首先把区间以右端点从小到大排序,以右端点设置雷达,如果下一个区间的左端点大于这个雷达,

就新建一个雷达(以新区间的右端点)。

在这里插入图片描述

在这里插入图片描述

Code:

#pragma GCC optimiza(2) 
#include <iostream>
#include <cstdio>
#include <cmath>
#include <queue>
#include <cstring>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#define inf 0x3f3f3f3f
#define eps 1e-6
using namespace std;
typedef long long int ll;
const int maxn = 70000;

pair<double,double> seg[maxn];

int main(){
    int n,d;
    cin>>n>>d;
    int flag=0;
    for(int i=1;i<=n;i++){
    	int x,y;
    	cin>>x>>y;
    	if(y>d) flag=1;
    	double len=sqrt(d*d-y*y);
    	seg[i]={x+len,x-len};  //(右端点,左端点)
	}
	if(flag) cout<<-1<<endl;
	
	else{
		sort(seg+1,seg+1+n); //右端点从小到大
		int ans=0;
		double pos=-inf;
		for(int i=1;i<=n;i++){
			if(seg[i].second>pos+eps) { //左端点大于雷达,即在雷达探测外,eps要注意范围精度问题
				ans++;
				pos=seg[i].first;
			}
		}
		cout<<ans<<endl;
	}
	return 0;
}



猜你喜欢

转载自blog.csdn.net/weixin_43872264/article/details/107544140