动态树有些类似 树链剖分+并查集 的思想,是用splay维护的
lct的根是动态的,"轻重链"也是动态的,所以并没有真正的轻重链
动态树的操作核心是把你要把 修改/询问/... 等等一系列的操作的树链放到一个splay里,然后用splay根据相对深度大小来维护这个树链
lct利用了splay的神奇性质,通过"认爹不认子"来达到记录多个子树的目的
lct的核心,access函数的意义是,在从这个点到它所在联通块中 相对深度最小的点 (可以理解为子树根) 的树链上,打通树链上每个点所在的splay树,并把需要的那部分树链放到一个splay树里,这样,这颗树链上的所有点就都在同一个splay里了,而且这颗splay里只存了这个树链而没有其他的点
由于根是动态的,所以有了makeroot函数,意义是把x点作为树根,先用access把需要的一部分树链取出,然后splay到根,发现x点原来是这条树链深度最大的点,现在深度变成了最小,用splay维护一下区间翻转即可
还有很多细节需要注意,洛谷上神犇的讲解很详细
#include <cstdio>
#include <algorithm>
#include <cstring>
#define root d[0].ch[1]
#define il inline
#define nu 7777
#define inf 500000
#define N 300100
using namespace std;
int n,m,tp;
int stk[N];
char str[10];
struct Link_Cut_Tree{
int fa[N],ch[N][2],sum[N],val[N],rev[N];
il int idf(int x){return ch[fa[x]][0]==x?0:1;}
il int isroot(int x){return (ch[fa[x]][0]!=x&&ch[fa[x]][1]!=x)?1:0;}
il void con(int x,int ff,int p){fa[x]=ff;ch[ff][p]=x;}
il void pushup(int x){sum[x]=sum[ch[x][0]]^sum[ch[x][1]]^val[x];}
il void revers(int x){swap(ch[x][0],ch[x][1]),rev[x]^=1;}
il void pushdown(int x){
if(rev[x]){
if(ch[x][0]) revers(ch[x][0]);
if(ch[x][1]) revers(ch[x][1]);
rev[x]=0;}}
il void rot(int x){
int y=fa[x];int ff=fa[y];int px=idf(x);int py=idf(y);
if(!isroot(y)) ch[ff][py]=x;
fa[x]=ff,con(ch[x][px^1],y,px),con(y,x,px^1);
pushup(y),pushup(x);}
void splay(int x){
int y=x;stk[++tp]=x;
while(!isroot(y)){stk[++tp]=fa[y];y=fa[y];}
while(tp){pushdown(stk[tp--]);}
while(!isroot(x)){
y=fa[x];
if(isroot(y)) rot(x);
else if(idf(y)==idf(x)) rot(y),rot(x);
else rot(x),rot(x);
}}
il void access(int x){for(int y=0;x;y=x,x=fa[x])splay(x),ch[x][1]=y,pushup(x);}
il void mkroot(int x){access(x),splay(x),revers(x);}
il int findrt(int x){
access(x),splay(x);
while(ch[x][0])pushdown(x),x=ch[x][0];
return x;}
il void split(int x,int y){mkroot(x),access(y),splay(y);}
il void link(int x,int y){mkroot(x);if(findrt(y)!=x)fa[x]=y;}
il void cut(int x,int y){
mkroot(x);
if(findrt(y)==x&&fa[x]==y&&!ch[x][1])
fa[x]=ch[y][0]=0,pushup(y);}
}lct;
int gc()
{
int rett=0,fh=1;char c=getchar();
while(c<'0'||c>'9'){if(c=='-')fh=-1;c=getchar();}
while(c>='0'&&c<='9'){rett=(rett<<3)+(rett<<1)+c-'0';c=getchar();}
return rett*fh;
}
int main()
{
n=gc(),m=gc();
for(int i=1;i<=n;i++) lct.val[i]=gc();
int fl,x,y;
for(int i=1;i<=m;i++)
{
fl=gc(),x=gc(),y=gc();
if(fl==0) lct.split(x,y),printf("%d\n",lct.sum[y]);
if(fl==1) lct.link(x,y);
if(fl==2) lct.cut(x,y);
if(fl==3) lct.splay(x),lct.val[x]=y,lct.pushup(x);
}
return 0;
}