Link Cut Tree

Posted mysblogs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Link Cut Tree相关的知识,希望对你有一定的参考价值。

Link Cut Tree留坑

LCT:

LCT模板

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#include<cmath>
#include<map>
#include<bitset>
#define rep(i,a,b) for(int i=(a);i<=(b);++i)
#define dwn(i,a,b) for(int i=(a);i>=(b);--i)
using namespace std;
typedef long long ll;
const int N=300000;
int n,m,fa[N+10],v[N+10],sum[N+10],ch[N+10][2],st[N+10];
bool rev[N+10];
inline int read()

    int x=0,f=1;
    char ch=getchar();
    while(ch<'0'||ch>'9')
    
        if(ch=='-') f=-1;
        ch=getchar();
    
    while(ch>='0'&&ch<='9')
    
        x=(x<<3)+(x<<1)+(ch^48);
        ch=getchar();
    
    return x*f;

inline bool isroot(int x)return !(ch[fa[x]][0]==x||ch[fa[x]][1]==x);
inline void pushup(int x)sum[x]=sum[ch[x][0]]^sum[ch[x][1]]^v[x];
inline void pushrev(int x)rev[x]^=1;swap(ch[x][0],ch[x][1]);
inline void pushdown(int x)

    if(rev[x])
    
        rev[x]=0;
        if(ch[x][0]) pushrev(ch[x][0]);
        if(ch[x][1]) pushrev(ch[x][1]);
    

inline int ident(int x)return x==ch[fa[x]][0]?0:1;
inline void rotate(int x)

    int Y=fa[x],R=fa[Y],Yson=ident(x),Rson=ident(Y);
    if(!isroot(Y)) ch[R][Rson]=x;
    if(ch[x][Yson^1]) fa[ch[x][Yson^1]]=Y;
    ch[Y][Yson]=ch[x][Yson^1];
    ch[x][Yson^1]=Y;
    fa[Y]=x;
    fa[x]=R;
    pushup(Y);pushup(x);

inline void splay(int x)

    int y=x,cnt=0;
    st[++cnt]=y;
    while(!isroot(y)) st[++cnt]=fa[y],y=fa[y];
    while(cnt) pushdown(st[cnt--]);
    while(!isroot(x))
    
        y=fa[x];
        if(isroot(y)) rotate(x);
        else if(ident(x)==ident(y)) rotate(y),rotate(x);
        else rotate(x),rotate(x);
    

inline void access(int x)

    for(int y=0;x;x=fa[y=x])
        splay(x),ch[x][1]=y,pushup(x);

inline void makeroot(int x)

    access(x),splay(x),pushrev(x);

inline int findroot(int x)

    access(x),splay(x);
    while(ch[x][0]) pushdown(x),x=ch[x][0];
    splay(x);
    return x;

inline void split(int x,int y)

    makeroot(x),access(y),splay(y);

inline void link(int x,int y)

    makeroot(x);
    if(findroot(y)!=x) fa[x]=y;

inline void cut(int x,int y)

    makeroot(x);
    if(findroot(y)!=x||fa[y]!=x||ch[y][0]) return;
    fa[y]=ch[x][1]=0;
    pushup(x);

int main()

    n=read(),m=read();
    rep(i,1,n) v[i]=read();
    rep(i,1,m)
    
        int opt=read(),x=read(),y=read();
        if(opt==0)split(x,y);printf("%d\n",sum[y]);
        if(opt==1)link(x,y);
        if(opt==2)cut(x,y);
        if(opt==3)splay(x);v[x]=y;pushup(x);
    
    return 0;

以上是关于Link Cut Tree的主要内容,如果未能解决你的问题,请参考以下文章

Link-Cut-Tree 动态树算法

Link/cut Tree

Link Cut Tree学习笔记

Link Cut Tree

Link Cut Tree

Link-cut-Tree