精华

文艺平衡树

YIZHIYANG初来乍到 2026-6-7 10:32:24 28 浏览 2 点赞 0 收藏
// Problem: P3391 【模板】文艺平衡树
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P3391
// Memory Limit: 125 MB
// Time Limit: 1000 ms
// by 1zhio2
// 
// Powered by CP Editor (https://cpeditor.org)

#include<bits/stdc++.h>
using namespace std;
using ll = long long;

const int N = 100005;

int n, m, rt, tot;
int ch[N][2], sz[N], va[N], ky[N], tg[N];

mt19937 rnd(71236721);

int nw(int v) {
    ++tot;
    va[tot] = v;
    sz[tot] = 1;
    ky[tot] = rnd();
    return tot;
}

void pu(int x) {
    sz[x] = sz[ch[x][0]] + sz[ch[x][1]] + 1;
}

void rv(int x) {
    if (!x) return;

    swap(ch[x][0], ch[x][1]);
    tg[x] ^= 1;
}

void pd(int x) {
    if (!tg[x]) return;

    rv(ch[x][0]);
    rv(ch[x][1]);
    tg[x] = 0;
}

void sp(int u, int k, int &x, int &y) {
    if (!u) {
        x = y = 0;
        return;
    }

    pd(u);

    int lz = sz[ch[u][0]];

    if (k <= lz) {
        y = u;
        sp(ch[u][0], k, x, ch[u][0]);
        pu(y);
    } else {
        x = u;
        sp(ch[u][1], k - lz - 1, ch[u][1], y);
        pu(x);
    }
}

int mg(int x, int y) {
    if (!x || !y) return x + y;

    if (ky[x] < ky[y]) {
        pd(x);
        ch[x][1] = mg(ch[x][1], y);
        pu(x);
        return x;
    } else {
        pd(y);
        ch[y][0] = mg(x, ch[y][0]);
        pu(y);
        return y;
    }
}

void dfs(int x) {
    if (!x) return;

    pd(x);
    dfs(ch[x][0]);
    cout << va[x] << " ";
    dfs(ch[x][1]);
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    cin >> n >> m;

    for (int i = 1; i <= n; i++) rt = mg(rt, nw(i));

    while (m--) {
        int l, r;
        cin >> l >> r;

        int a, b, c, d;

        sp(rt, l - 1, a, b);
        sp(b, r - l + 1, c, d);

        rv(c);

        rt = mg(a, mg(c, d));
    }

    dfs(rt);
    return 0;
}

评论

0 条
还没有评论。