[算法模版]Link-Cut-Tree
[算法模版]Link-Cut-Tree
博主懶本博客只對(duì)現(xiàn)有博客進(jìn)行補(bǔ)充,先直接放隔壁鏈接。
FlashHu-LCT總結(jié)
Menci-LCT學(xué)習(xí)筆記
make-root操作
make-root操作用于把任何一個(gè)點(diǎn)反轉(zhuǎn)到當(dāng)前樹的根節(jié)點(diǎn)。
做法是先把要進(jìn)行操作的節(jié)點(diǎn)x進(jìn)行access,將root和x進(jìn)行連通。然后進(jìn)行splay(x)操作,把x變成splay的根。(請(qǐng)注意,這時(shí)候x在主樹的深度仍然沒有改變)。
隨后將x的子樹全部進(jìn)行反轉(zhuǎn)操作。也就是改變了這個(gè)splay的深度。雖然splay和splay之間的連接需要依賴深度關(guān)系(一棵splay的虛邊連接向當(dāng)前splay中序遍歷序列的首位在原樹上的父親)。但是因?yàn)橄鄬?duì)關(guān)系不變,所以不影響。
看圖(圖來自 動(dòng)態(tài)仙人掌系列題解之四):
可以把連接老根和新根的splay看作一個(gè)無法彎曲的桿子,其他splay都是連接在桿子上的塊。旋轉(zhuǎn)操作雖然會(huì)改變桿子上每一點(diǎn)的深度,但是卻不會(huì)改變塊和桿子上連接點(diǎn)的相對(duì)深度關(guān)系。所以不會(huì)這樣變換老根和新根不會(huì)對(duì)樹的結(jié)構(gòu)造成破壞。
代碼
洛谷3690
#include<iostream> #include<cstdio> #include<algorithm> #include<cmath> #define maxn (int)(3e5+1000) int f[maxn],v[maxn],s[maxn],st[maxn],c[maxn][2]; bool r[maxn]; using namespace std; int n,m; void pushr(int x){swap(c[x][0],c[x][1]);r[x]^=1; } void pushdown(int x){if(!r[x])return;if(c[x][0])pushr(c[x][0]);if(c[x][1])pushr(c[x][1]);r[x]=0; } void pushup(int x){s[x]=s[c[x][0]]^s[c[x][1]]^v[x]; }bool nroot(int x){return c[f[x]][0]==x||c[f[x]][1]==x; } void rotate(int x){int y=f[x],z=f[y],k=(c[y][1]==x),w=c[x][!k];bool flag=nroot(y);c[y][k]=c[x][!k];f[c[x][!k]]=y;c[x][!k]=y;f[y]=x;if(flag)c[z][c[z][1]==y]=x;f[x]=z;pushup(y);pushup(x); } void splay(int x){int y=x,z=0;st[++z]=y;while(nroot(y))st[++z]=y=f[y];while(z)pushdown(st[z--]);for(;nroot(x);rotate(x)){y=f[x];if(!nroot(f[x]))continue;rotate((c[f[x]][0]==x)==(c[f[y]][0]==y)?y:x);}// pushup(x); } void access(int x){for(int y=0;x;y=x,x=f[x]){splay(x);c[x][1]=y;pushup(x);} } int findroot(int x){access(x);splay(x);while(c[x][0]){pushdown(x);x=c[x][0];}splay(x);return x; } void makeroot(int x){access(x);splay(x);pushr(x); } void split(int x,int y){makeroot(x);access(y);splay(y); } void link(int x,int y){if(findroot(x)!=findroot(y)){makeroot(x);f[x]=y;} } void cut(int x,int y){makeroot(x);if(findroot(y)==x&&f[y]==x&&!c[y][0]){f[y]=c[x][1]=0;pushup(x);} } int main(){scanf("%d%d",&n,&m);for(int i=1;i<=n;i++)scanf("%d",&v[i]);for(int i=1;i<=m;i++){int ty,x,y;scanf("%d%d%d",&ty,&x,&y);if(ty==0){split(x,y);printf("%d\n",s[y]);}else if(ty==1){link(x,y);}else if(ty==2){cut(x,y);}else if(ty==3){splay(x);v[x]=y;//pushup(x);}} }轉(zhuǎn)載于:https://www.cnblogs.com/GavinZheng/p/11149166.html
總結(jié)
以上是生活随笔為你收集整理的[算法模版]Link-Cut-Tree的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: QSetting介绍
- 下一篇: 0708---oop学习--用户密码管理