【ybtoj】【貪心】【例題2】雷達裝置
阿新 • • 發佈:2020-12-26
>解題思路
以建築物為中心畫半徑為
d
d
d的圓,確定一個在
x
x
x軸上的區間,只要在這個區間內的雷達一定能掃到這個建築物
l
l
l和
r
r
r可以根據勾股定理求,
l
=
x
−
d
2
+
y
2
l=x-\sqrt{d^2+y^2}
l=x−d2+y2
,
r
=
x
+
d
2
+
y
2
r=x+\sqrt{d^2+y^2}
r=x+d2+y2
將區間按右端點從小到大排序
預設將雷達放在右端點上,如果最後一個雷達沒有掃到當前點(不在當前點的區間內),那麼就增加一個雷達
>Code
#include < algorithm>
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
struct DT {
double x, y;
} a[1100];
long long n, d, ans;
double b[1100], x[1100], y[1100];
bool cmp(const DT& k, const DT& l) { return (k.y < l.y); }
int main() {
scanf("%lld%lld" , &n, &d);
for (int i = 1; i <= n; i++) {
scanf("%lf%lf", &x[i], &y[i]);
if (abs(y[i]) > d) {//如果高度超過d,一定掃不到
printf("-1");
return 0;
}
a[i].x = x[i] - sqrt(d * d - y[i] * y[i]);//求l和r
a[i].y = x[ i] + sqrt(d * d - y[i] * y[i]);
}
sort(a + 1, a + 1 + n, cmp);
b[++ans] = a[1].y;//預設將端點放在右端點上
for (int i = 2; i <= n; i++)
if (b[ans] < a[i].x)//如果雷達不在區間內(掃不到當前點)
b[++ans] = a[i].y;//加入一個雷達,也是放在右端點上
printf("%lld", ans);
}