其他分享
首页 > 其他分享> > Link-Cut-Tree(1)

Link-Cut-Tree(1)

作者:互联网

参考论文

求解范围:(动态树问题)

算法逻辑

概念:

流程:

access

void access(int x) {
	int y=0;
	while(x) {
		splay(x);P_dw(x);
		if(son[x][1]) fa[son[x][1]]=0,par[son[x][1]]=x;
		son[x][1]=y;fa[y]=x;	//??splay
		P_up(x);
		y=x;x=par[x];
	}
}

LCA(x,y)

小细节

ps.还有很多其余的操作可以见下面这道题的代码:
OTOCI

    #include<bits/stdc++.h>
    using namespace std;
    const int N=1e6+5;
    bool Lazy[N];
    int val[N],son[N][2],sum[N];
    int par[N],fa[N];
    int q,n;
    void P_up(int x) {sum[x]=val[x]+sum[son[x][0]]+sum[son[x][1]];}
    void P_dw(int x) {
    	if(!Lazy[x])return;
    	swap(son[x][0],son[x][1]);
    	Lazy[son[x][0]]^=1,Lazy[son[x][1]]^=1;Lazy[x]=0;
    }
    bool Type(int x) {return son[fa[x]][1]==x;}
    void rotate(int x) {
    	int y=fa[x],z=fa[y],k=Type(x);
    	fa[x]=z;if(z)son[z][Type(y)]=x;
    	son[y][k]=son[x][k^1];fa[son[y][k]]=y;
    	son[x][k^1]=y;fa[y]=x;
    	P_up(y);P_up(x);
    }
    void _spdw(int u,int x) {
    	if(!fa[u]) {par[x]=par[u];P_dw(u);return;}
    	_spdw(fa[u],x);
    	P_dw(u);
    }
    void splay(int x) {
    	_spdw(x,x);
    	for(int f=fa[x];f=fa[x];rotate(x)) {
    		if(fa[f]) rotate(Type(x)==Type(f)?f:x);
    	}
    }
    void access(int x) {
    	int y=0;
    	while(x) {
    		splay(x);P_dw(x);
    		if(son[x][1]) fa[son[x][1]]=0,par[son[x][1]]=x;
    		son[x][1]=y;fa[y]=x;	//??splay
    		P_up(x);
    		y=x;x=par[x];
    	}
    }
    void mk_rt(int x) {access(x);splay(x);Lazy[son[x][0]]^=1;Lazy[son[x][1]]^=1;swap(son[x][0],son[x][1]);}
    int Fd_rt(int x) {access(x);splay(x);while(son[x][0])x=son[x][0];splay(x);return x;}
    void split(int x,int y)	{mk_rt(x);access(y);splay(y);}	//??
    void Link(int x,int y) {mk_rt(x);par[x]=y;}
    int Sum(int x,int y) {split(x,y);return sum[y];}
    int main() {
    	scanf("%d",&n);
    	for(int i=1;i<=n;i++) scanf("%d",&val[i]),sum[i]=val[i];
    	scanf("%d",&q);
    	while(q--) {
    		char ch[21]; int x,y;
    		scanf("%s%d%d",ch,&x,&y);
    		if(ch[0]=='b') {
    //			printf("!%d %d\n",Fd_rt(x),Fd_rt(y));
    			if(Fd_rt(x)!=Fd_rt(y)) {printf("yes\n");Link(x,y);}
    			else printf("no\n");
    		}
    		else if(ch[0]=='p') {
    			splay(x);val[x]=y;P_up(x);
    		}
    		else {
    //			printf("!%d %d\n",Fd_rt(x),Fd_rt(y));
    			if(Fd_rt(x)!=Fd_rt(y)) {printf("impossible\n");continue;}
    			printf("%d\n",Sum(x,y));
    		}
    	}
    	return 0;
    }

标签:par,Cut,int,void,Tree,son,splay,fa,Link
来源: https://www.cnblogs.com/bestime/p/15769048.html