跳到正文

题解

P4148 简单题 题解

Argvchs约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年3月5日
收录
2026年3月7日
更新
2026年11月16日
篇幅
约 5 分钟
获赞
6
题目
P4148

版本

  1. v2当前
  2. v1

根号重构,每次重构将坐标离散化为排列使得 x,yx, y 唯一对应,然后将二维平面按照 n×n\sqrt n \times \sqrt n 的矩形分块,预处理二维前缀和,查询时整块直接做,散块由于 x,yx, y 唯一对应所以复杂度也是对的。时间复杂度 O(nn)O(n \sqrt n),空间复杂度 O(n)O(n)。

实际上这样做跑的飞快,可以拿到目前的最优解。

https://www.luogu.com.cn/record/265501832

C++
#include <cmath>
#include <iostream>
using namespace std;
const int N = 5e5 + 5, M = 2e5 + 5, B = 450, S = M / B + 5;
int n, m, a[M], b[M], c[M], la[N], ra[N], lb[N], rb[N], ab[M], ba[M], ac[M], bc[M], bel[M],
    sum[S][S], siz, cnt, lst;
void rebuild() {
    siz = sqrt(m = cnt);
    for (int i = 1; i <= n; i++) ra[i] = rb[i] = 0;
    for (int i = 1; i <= m; i++) ++ra[a[i]], ++rb[b[i]];
    for (int i = 1; i <= n; i++)
        la[i] = ra[i - 1] + 1, ra[i] += ra[i - 1], lb[i] = rb[i - 1] + 1, rb[i] += rb[i - 1];
    for (int i = 1; i <= m; i++) bel[i] = (i - 1) / siz + 1;
    for (int i = 1; i <= bel[m]; i++)
        for (int j = 1; j <= bel[m]; j++) sum[i][j] = 0;
    for (int i = 1; i <= m; i++) {
        int x = la[a[i]]++, y = lb[b[i]]++;
        ab[x] = y, ba[y] = x, sum[bel[x]][bel[y]] += ac[x] = bc[y] = c[i];
    }
    for (int i = 1; i <= bel[m]; i++)
        for (int j = 1; j <= bel[m]; j++)
            sum[i][j] += sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1];
}
int query_(int x, int y) {
    if (!x || !y) return 0;
    int ret = sum[bel[x] - 1][bel[y] - 1];
    for (int i = siz * (bel[x] - 1) + 1; i <= x; i++)
        if (ab[i] <= y) ret += ac[i];
    for (int i = siz * (bel[y] - 1) + 1; i <= y; i++)
        if (ba[i] <= siz * (bel[x] - 1)) ret += bc[i];
    return ret;
}
int query(int x, int y) { return query_(ra[x], rb[y]); }
int query(int x1, int y1, int x2, int y2) {
    int ret = query(x2, y2) - query(x2, y1 - 1) - query(x1 - 1, y2) + query(x1 - 1, y1 - 1);
    for (int i = m + 1; i <= cnt; i++)
        if (x1 <= a[i] && a[i] <= x2 && y1 <= b[i] && b[i] <= y2) ret += c[i];
    return ret;
}
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cin >> n;
    for (int op, x1, y1, x2, y2, k; cin >> op && op != 3;) {
        cin >> x1 >> y1, x1 ^= lst, y1 ^= lst;
        if (op == 1) cin >> k, a[++cnt] = x1, b[cnt] = y1, c[cnt] = k ^= lst;
        else {
            cin >> x2 >> y2, x2 ^= lst, y2 ^= lst;
            if (cnt - m > B) rebuild();
            cout << (lst = query(x1, y1, x2, y2)) << '\n';
        }
    }
}
原文
存档评论2 条抓取于