码迷,mamicode.com
首页 > 其他好文 > 详细

【模板】Link-Cut Tree

时间:2018-01-11 20:36:49      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:bool   opened   maker   include   img   str   efi   link   swa   

 

技术分享图片
 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

标签:bool   opened   maker   include   img   str   efi   link   swa   

原文地址:https://www.cnblogs.com/DriverLao/p/8270084.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!