模板Link-Cut Tree

Posted Driver_Lao

tags:

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

 

技术分享图片
 1 #include<cstdio>
 2 #include<algorithm>
 3 #define N 500010
 4 #define ls (c[u][0])
 5 #define rs (c[u][1])
 6 using namespace std;
 7 int n,m,opt,val[N];
 8 inline int read(){
 9     int k=0,f=1; char c=getchar();
10     while(c<0||c>9)c==-&&(f=-1),c=getchar();
11     while(0<=c&&c<=9)k=k*10+c-0,c=getchar();
12     return k*f;
13 }
14 struct Link_Cut_Tree{
15     int top,c[N][2],fa[N],xr[N],q[N],rev[N];
16     inline void pushup(int u){xr[u]=xr[ls]^xr[rs]^val[u];}
17     inline void pushdown(int u){if(rev[u]) rev[ls]^=1,rev[rs]^=1,rev[u]^=1,swap(ls,rs);}
18     inline bool isroot(int u){return c[fa[u]][0]!=u&&c[fa[u]][1]!=u;}
19     inline bool which(int u){return c[fa[u]][1]==u;}
20     void rotate(int u){
21         int f=fa[u],gf=fa[f],wh=which(u);
22         if(!isroot(f)){c[gf][which(f)]=u;}
23         fa[u]=gf; fa[f]=u; fa[c[u][wh^1]]=f;
24         c[f][wh]=c[u][wh^1]; c[u][wh^1]=f;
25         pushup(f); pushup(u);
26     }
27     void splay(int u){
28         top=1; q[top]=u;
29         for(int i=u;!isroot(i);i=fa[i]) q[++top]=fa[i];
30         for(int i=top;i;i--) pushdown(q[i]);
31         while(!isroot(u)){
32             if(!isroot(fa[u])) rotate(which(u)==which(fa[u])?fa[u]:u);
33             rotate(u);
34         }
35     }
36     void access(int u){
37         for(int son=0;u;son=u,u=fa[u]) splay(u),c[u][1]=son,pushup(u);
38     }
39     void makeroot(int u){
40         access(u); splay(u); rev[u]^=1;
41     }
42     int find(int u){
43         access(u); splay(u);
44         while(ls) u=ls; return u;
45     }
46     void split(int x,int y){
47         makeroot(x); access(y); splay(y);
48     }
49     void cut(int x,int y){
50         split(x,y); 
51         if(c[y][0]==x) c[y][0]=0,fa[x]=0;
52     }
53     void link(int x,int y){
54         makeroot(x); fa[x]=y;
55     }
56 }t;
57 int main(){
58     n=read(); m=read();
59     for(int i=1;i<=n;i++) val[i]=t.xr[i]=read();
60     while(m--){
61         if((opt=read())==0){
62             int x=read(),y=read(); 
63             t.split(x,y);
64             printf("%d\n",t.xr[y]);
65         }
66         if(opt==1){
67             int x=read(),y=read(),xx=t.find(x),yy=t.find(y);
68             if(xx!=yy) t.link(x,y);
69         }
70         if(opt==2){
71             int x=read(),y=read(),xx=t.find(x),yy=t.find(y);
72             if(xx==yy) t.cut(x,y);
73         }
74         if(opt==3){
75             int x=read(),y=read();
76             t.access(x); t.splay(x); val[x]=y; t.pushup(x);
77         }
78     }
79     return 0;
80 }
View Code

洛谷3690

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

以 BZOJ 2002 为例学习有根树LCT(Link-Cut Tree)

BZOJ2555SubString(后缀自动机,Link-Cut Tree)

Link-Cut Tree

SPOJQTREE7(Link-Cut Tree)

动态树Link-Cut Tree(LCT)

QTREE5 Link-Cut Tree