【洛谷 P2147】 [SDOI2008]洞穴勘测(LCT)

本文深入解析了LCT树的原理与应用,通过一道LCT裸题实战演示了LCT树的编码实现过程,包括节点旋转、路径压缩等关键操作,以及如何利用LCT树解决复杂的动态树形结构问题。

题目链接
LCT裸题。。

#include <cstdio>
#define R register int
#define I inline void
#define lc c[x][0]
#define rc c[x][1]
const int MAXN = 300010;
inline int read(){
    int s = 0, w = 1;
    char ch = getchar();
    while(ch < '0' || ch > '9'){ if(ch == '-') w = -1; ch = getchar(); }
    while(ch >= '0' && ch <= '9'){ s = s * 10 + ch - '0'; ch = getchar(); }
    return s * w;
}
int f[MAXN], c[MAXN][2], v[MAXN], s[MAXN], st[MAXN], tag[MAXN];
inline int nroot(R x){
    return c[f[x]][0] == x || c[f[x]][1] == x;
}
I swap(R x){
    lc ^= rc; rc = lc ^ rc; lc ^= rc; tag[x] ^= 1;
}
I pushdown(R x){
    if(tag[x]){
        swap(lc); swap(rc);
        tag[x] = 0;
    }
}
I rotate(R x){
    R y = f[x], z = f[y], k = c[y][1] == x, w = c[x][!k];
    if(nroot(y)) c[z][c[z][1] == y] = x;
    c[x][!k] = y; c[y][k] = w; f[y] = x; f[x] = z;
    if(w) f[w] = y;
}
I splay(R x){
    R y = x, z = 0;
    st[++z] = y;
    while(nroot(y)) st[++z] = y = f[y];
    while(z) pushdown(st[z--]);
    while(nroot(x)){
        y = f[x]; z = f[y];
        if(nroot(y)) (c[z][1] == y) ^ (c[y][1] == x) ? rotate(x) : rotate(y);
        rotate(x);
    }
}
I access(R x){
    for(R y = 0; x; x = f[y = x]){
       splay(x); rc = y; 
    }
}
I makeroot(R x){
    access(x); splay(x); 
    swap(x);
}
inline int findroot(R x){
    access(x); splay(x);
    pushdown(x);
    while(lc){ x = lc; pushdown(x); }
    splay(x);
    return x;
}
I split(R x, R y){
    makeroot(x); access(y); splay(y);
}
I link(R x, R y){
    makeroot(x);
    f[x] = y;
}
I cut(R x, R y){
    split(x, y);
    f[x] = c[y][0] = 0;
}
int n, m, a, b;
char opt;
int main(){
    n = read(); m = read();
    while(m--){
        opt = getchar(); while(opt < 'A' || opt > 'Z') opt = getchar();
        a = read(); b = read();
        switch(opt){
            case 'C' : link(a, b); break;
            case 'D' : cut(a, b); break;
            case 'Q' : printf("%s\n", findroot(a) == findroot(b) ? "Yes" : "No");
        }
    }
    return 0;
}

转载于:https://www.cnblogs.com/Qihoo360/p/10331446.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值