跳到正文

个人记录

扫描线 - 树状数组实现

zykaris约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟

版本

  1. v1当前
C++
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 1e5 + 5;

int n;
ll ans;
ll y[N << 1];
int c[N << 1];
vector<array<ll, 4>> e;

void u(int i, int d) {
    for (; i < n * 2 + 1; i += i & -i) c[i] += d;
}

int q(int i) {
    int s = 0;
    for (; i; i -= i & -i) s += c[i];
    return s;
}

int qr(int l, int r) { return q(r) - q(l - 1); }

int main() {
    cin >> n;
    for (int i = 0; i < n; ++i) {
        ll x1, y1, x2, y2;
        cin >> x1 >> y1 >> x2 >> y2;
        y[i * 2] = y1; y[i * 2 + 1] = y2;
        e.push_back({x1, y1, y2, 1});
        e.push_back({x2, y1, y2, -1});
    }

	sort(y, y + 2 * n);

	int m = unique(y, y + 2 * n) - y;
    auto get = [&](ll yy) {
        return lower_bound(y, y + m, yy) - y + 1;
    };

	sort(e.begin(), e.end());

	for (int i = 0; i < e.size(); ++i) {
        auto [x, y1, y2, t] = e[i];
        int l = get(y1), r = get(y2);
        u(l, t);
        u(r, -t);
        ll len = 0;
        for (int j = 1; j < m; ++j) {
            if (q(j) > 0) {
                len += y[j] - y[j - 1];
            }
        }
        ll nx = (i + 1 < e.size()) ? e[i + 1][0] : x;
        ans += len * (nx - x);
    }

    cout << ans << endl;
    return 0;
}
原文