尚未完成的LCT

#include <iostream>
#include <algorithm>

using namespace std;

const int MaxN = 1e5 + 10;

struct Node {
    int ch[2], fa, w, x, tag;
} a[MaxN];

int n, m;

inline bool rs(int x) { return a[a[x].fa].ch[1] == x; }
inline bool nr(int x) { return a[a[x].fa].ch[0] == x || a[a[x].fa].ch[1] == x; }
inline void reves(int x) { a[x].tag ^= 1; }

int pushdown(int k) {
    if (!a[k].tag) return k;
    swap(a[k].ch[0], a[k].ch[1]);
    reves(a[k].ch[0]), reves(a[k].ch[1]);
    return a[k].tag = 0;
}

int update(int k) {
    pushdown(a[k].ch[0]), pushdown(a[k].ch[1]);
    return a[k].w = a[a[k].ch[0]].w ^ a[a[k].ch[1]].w ^ a[k].x, k;
}

int rotatr(int x, int y = 0, int z = 0, int flag = 0) {
    y = a[x].fa, z = a[y].fa, flag = rs(x);
    (nr(y)) && (a[z].ch[rs(y)] = x), a[x].fa = z;
    a[y].ch[flag] = a[x].ch[flag ^ 1], (a[x].ch[flag ^ 1]) && (a[a[x].ch[flag ^ 1]].fa = y);
    a[x].ch[flag ^ 1] = y, a[y].fa = x;
    return update(y);
}

void pushall(int x) {
    int stk[MaxN], top = 0;
    int y = x;
    while (nr(y)) stk[top++] = y, y = a[y].fa;
    stk[top++] = y;
    while (top) pushdown(stk[--top]);
}

int splay(int x) {
    pushall(x);
    while (nr(x)) {
        int y = a[x].fa;
        if (nr(y)) {
            int z = a[y].fa;
            if (rs(x) == rs(y)) rotatr(y); // Zig-Zig
            else rotatr(x); // Zig-Zag
        }
        rotatr(x); // Zig
    }
    return update(x);
}

void access(int x) {
    for (int y = 0; x; y = x, x = a[x].fa) {
        splay(x), a[x].ch[1] = y, update(x);
    }
}

void makeroot(int x) {
    access(x), splay(x), reves(x);
}

int findroot(int x) {
    access(x), splay(x), pushdown(x);
    while (a[x].ch[0]) pushdown(x), x = a[x].ch[0];
    return splay(x);
}

void split(int x, int y) {
    makeroot(x), access(y), splay(y);
}

void link(int x, int y) {
    makeroot(x);
    if (findroot(y) == x) return;
    a[x].fa = y;
}

void cut(int x, int y) {
    makeroot(x);
    if (findroot(y) != x || a[y].fa != x || a[y].ch[0]) return;
    a[y].fa = a[x].ch[1] = 0, splay(x);
}

int main() {
    ios::sync_with_stdio(0), cin.tie(0);
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        a[i] = Node{{0, 0}, 0, 0, 0, 0};
        cin >> a[i].x;
        a[i].w = a[i].x;
    }
    for (int i = 1, op, x, y; i <= m; i++) {
        cin >> op >> x >> y;
        if (!op) {
            split(x, y);
            cout << a[y].w << '\n';
        } else if (op == 1) {
            link(x, y);
        } else if (op == 2) {
            cut(x, y);
        } else {
            splay(x), a[x].x = y;
        }
    }
    return 0;
}

TLE#11

posted @ 2025-03-08 17:39  yabnto  阅读(12)  评论(1)    收藏  举报