以下是基本思路的C++代码实现:

#include #include

using namespace std;

int main() { double L, W; int n; cin >> L >> W >> n;

vector<pair<double, double>> sprinklers(n); // 存储喷头位置和覆盖范围
for (int i = 0; i < n; i++) {
    double position, radius;
    cin >> position >> radius;
    sprinklers[i] = make_pair(position, radius);
}

double left_edge = -W / 2.0; // 草坪左边缘
double right_edge = W / 2.0; // 草坪右边缘
double curr_pos = 0.0; // 当前位置
int count = 0; // 覆盖区域内喷头数量

for (int i = 0; i < n; i++) {
    double pos = sprinklers[i].first;
    double radius = sprinklers[i].second;

    // 如果喷头的位置在当前位置左侧,则不考虑该喷头
    if (pos <= curr_pos) continue;

    // 如果喷头的覆盖范围没有覆盖到当前位置,则需要添加一个喷头
    if (pos - radius > curr_pos) {
        cout << -1 << endl;
        return 0;
    }

    // 找到离当前位置最远的喷头
    double max_pos = pos + sqrt(radius * radius - (W / 2.0) * (W / 2.0));
    for (int j = i + 1; j < n; j++) {
        double next_pos = sprinklers[j].first;
        double next_radius = sprinklers[j].second;
        if (next_pos - next_radius > max_pos) break;
        max_pos = max(max_pos, next_pos + sqrt(next_radius * next_radius - (W / 2.0) * (W / 2.0)));
    }

    // 更新当前位置和喷头数量
    curr_pos = max_pos;
    count++;

    // 如果当前位置已经到达草坪右边缘,则不需要再添加喷头
    if (curr_pos >= right_edge) break;
}

// 如果当前位置还没有到达草坪右边缘,则需要添加喷头
if (curr_pos < right_edge) {
    cout << -1 << endl;
    return 0;
}

cout << count << endl;

return 0;
长 L 米宽 W 米的草坪里装有 n 个浇灌喷头。每个喷头都装在草坪中心线上离两边各 fracW2 米。我们知道每个喷头的位置离草坪中心线左端的距离以及它能覆盖到的浇灌范围。用c++代码写

原文地址: https://www.cveoy.top/t/topic/fkKK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录