在I米长w米宽的水平草坪上安装了n个洒水器。每个洒水喷头都安装在长条的水平中心线上。对于每个洒水车,我们都知道它的位置,即从中心线左端到它的距离和它的工作半径。为了给整个草坪浇水,最少需要打开多少个洒水器?
圆心为C,半径为R,草坪长度为L,宽度为W。
当洒水器的直径要小于等于草坪宽度时,这个洒水器相当于无效。
喷头覆盖的有效范围为[C- sqrt(R* R - 0.25 * W * W , C + sqrt (R*R - 0.25 * W *W)].
先按有效前区间进行从小到大排序
遍历时候注意以下几种情形
洒水器的最左端或最右端的有效区间,不能覆盖草坪的最左端最右端,则输出-1。
排序完成后中间出现断层,输出-1。
出现大圈套小圈,则选择大圈。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int N = 10010;
struct Seg {
double x;
double y;
friend bool operator < (const Seg& a, const Seg& b) {//重载操作符,自定义结构体小于号的比较
return a.x < b.x;//前有效区间小的排在前面
}
}seg[N];
int n;//n个喷头
double L, w;
void input() {
int sum = 0;
double p, r;
for (int i = 0; i < n; i++) {
cin >> p >> r;
if (w / 2 >= r) continue;//半径没超过宽度一半的要舍去
double q = sqrt(r * r - w * w / 4.0);//有效范围半径
seg[sum].x = p - q;//前有效区间
seg[sum].y = p + q;//后有效区间
sum++;
}
n = sum;
}
int main() {
while (scanf("%d%lf%lf", &n, &L, &w) == 3) {
memset(seg, 0, sizeof(seg));
input();//包含了输入n行操作
sort(seg, seg + n);//对结构体按规定的小于号排序
int cnt = 0;
double begin = 0, over = 0;
bool flag = false;
if (seg[0].x <= 0) {
int i = 0;
while (i < n) {
int j = i;
while (j < n && begin >= seg[j].x) {
if (seg[j].y > over)
over = seg[j].y;
j++;
}
if (i == j) break;
cnt++;
begin = over;
i = j;
if (begin >= L) {
flag = true;
break;
}
}
}
if (flag)
printf("%d\n", cnt);
else
printf("-1\n");
}
return 0;
}
代码: