1 条题解

  • 0
    @ 2026-11-2 10:56:32

    园丁的烦恼(The Gardeners Trouble) 题解

    思路分析

    按题目要求使用对应数据结构与算法模拟/递推求解,注意数据范围边界与时间复杂度。

    参考代码

    #include <algorithm>
    #include <iostream>
    #include <vector>
    using namespace std;
    
    struct Op {
        int x, y, type, id;
        bool operator<(const Op& o) const {
            if (x != o.x) return x < o.x;
            return type < o.type; // point (0) before query (+/-1)
        }
    };
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int n, m;
        if (!(cin >> n >> m)) return 0;
        vector<Op> ops;
        ops.reserve(n + 4 * m);
        vector<int> ys;
        ys.reserve(n + 2 * m);
        for (int i = 0; i < n; ++i) {
            int x, y;
            cin >> x >> y;
            ops.push_back({x, y, 0, 0});
            ys.push_back(y);
        }
        for (int i = 0; i < m; ++i) {
            int a, b, c, d;
            cin >> a >> b >> c >> d;
            ops.push_back({c, d, 1, i});
            ops.push_back({a - 1, d, -1, i});
            ops.push_back({c, b - 1, -1, i});
            ops.push_back({a - 1, b - 1, 1, i});
            ys.push_back(d);
            ys.push_back(b - 1);
        }
        sort(ys.begin(), ys.end());
        ys.erase(unique(ys.begin(), ys.end()), ys.end());
        sort(ops.begin(), ops.end());
    
        int K = (int)ys.size();
        vector<int> bit(K + 1, 0);
        auto add = [&](int idx, int v) {
            for (; idx <= K; idx += idx & -idx) bit[idx] += v;
        };
        auto sum = [&](int idx) {
            int s = 0;
            for (; idx > 0; idx -= idx & -idx) s += bit[idx];
            return s;
        };
    
        vector<int> ans(m, 0);
        for (const auto& op : ops) {
            int y_idx = (int)(lower_bound(ys.begin(), ys.end(), op.y) - ys.begin()) + 1;
            if (op.type == 0) {
                add(y_idx, 1);
            } else {
                ans[op.id] += op.type * sum(y_idx);
            }
        }
        for (int i = 0; i < m; ++i) cout << ans[i] << "\n";
        return 0;
    }
    
    • 1

    信息

    ID
    8586
    时间
    1500ms
    内存
    128MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者