问题


思路

根据勾股定理,当给定雷达的覆盖范围,对于每个岛屿座标,其在x轴上会有一个有效区间,在这个有效区间内的所有地方设置雷达,都能覆盖到这个岛屿,从而我们可以将每个点转换为每个区间,问题就转化为了至少选择多少个点,可以覆盖这些所有区间,经典的贪心求“区间选点”问题。
https://blog.csdn.net/weixin_45798993/article/details/123164244
整个算法的时间复杂度是排序的时间复杂度,即O ( n l o g n ) O(nlogn)O(nlogn)
代码
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
const int N=1010;
struct qj //定义区间结构体 属性为左端点和右端点
{
double l,r; //一定要定义成double类型,因为实际计算中经过了开平方,肯定是实数型,而不是int,用int会有错误
bool operator<(const qj &w)const //重载<号,按右端点排序
{
return r<w.r;
}
}qj[N];
int cnt,n,d;
int main()
{
scanf("%d%d",&n,&d);
for(int i=0;i<n;i++)
{
int a,b;
scanf("%d%d",&a,&b);
if(d<b) //特判特殊情况
{
printf("-1");
return 0;
}
qj[i]={a-sqrt(d*d-b*b),a+sqrt(d*d-b*b)};
}
sort(qj,qj+n);
int res=0;
double ed=-2e9; //这里也别忘了定义成double,因为这个变量用来保存右端点的
for(int i=0;i<n;i++)
{
if(qj[i].l>ed)
{
res++;
ed=qj[i].r;
}
}
printf("%d",res);
return 0;
}
版权声明:本文为weixin_45798993原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。