a999困難

覆蓋總面積(Area)(2016 全國資訊學科能力競賽)

計算矩形聯集而不重複加重疊。

解題思路

每個矩形產生左邊界加入、右邊界移除事件,將y端點壓縮成相鄰基本線段。掃描x時,兩事件x之間覆蓋情況固定。

線段樹每個節點存覆蓋次數cover與覆蓋長度len。cover>0時整段被覆蓋,len為原座標端點差;cover=0時若非葉則取兩孩子長度和。

先把目前根的覆蓋長度乘上這次與上次x差加入面積,再處理該x事件。每個垂直條帶各加一次,恰為聯集面積;相同x的事件間寬為0,故順序不影響面積。

O(N log N)時間、O(N)空間;面積用64位元。 Python一次讀入另佔O(輸入文字長度)空間。

Step-by-step animation

示例:[0,2]×[0,2]與[1,3]×[1,3]。

回報動畫錯誤
步驟 1 / 3

兩矩形

[0,2]×[0,2]與[1,3]×[1,3]。

x0:+[0,2]
x1:+[1,3]
x2:−[0,2]
x3:−[1,3]
面積
0

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
struct E {
    int x, y, z, d;
};
int main() {
    int n;
    cin >> n;
    vector<E> e;
    vector<int> y;
    for (int i = 0, a, b, c, d; i < n; i++) {
        cin >> a >> b >> c >> d;
        if (a == c || b == d)
            continue;
        e.push_back({a, b, d, 1});
        e.push_back({c, b, d, -1});
        y.push_back(b);
        y.push_back(d);
    }
    if (e.empty()) {
        cout << 0 << '\n';
        return 0;
    }
    sort(y.begin(), y.end());
    y.erase(unique(y.begin(), y.end()), y.end());
    int m = y.size() - 1;
    vector<int> cnt(4 * m + 4);
    vector<long long> len(4 * m + 4);
    function<void(int, int, int, int, int, int)> upd = [&](int p, int l, int r, int a,
                                                           int b, int d) {
        if (a <= l && r <= b)
            cnt[p] += d;
        else {
            int h = (l + r) / 2;
            if (a < h)
                upd(p * 2, l, h, a, b, d);
            if (b > h)
                upd(p * 2 + 1, h, r, a, b, d);
        }
        len[p] = cnt[p] ? y[r] - y[l] : (r - l == 1 ? 0 : len[p * 2] + len[p * 2 + 1]);
    };
    sort(e.begin(), e.end(), [](E a, E b) { return a.x < b.x; });
    long long ans = 0;
    int last = e[0].x;
    for (auto a : e) {
        ans += 1LL * (a.x - last) * len[1];
        int l = lower_bound(y.begin(), y.end(), a.y) - y.begin(),
            r = lower_bound(y.begin(), y.end(), a.z) - y.begin();
        upd(1, 0, m, l, r, a.d);
        last = a.x;
    }
    cout << ans << '\n';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多