【题解】
动态树模板题,只要求维护森林的连通性,直接上板子即可。
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; 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],rev[N],q[N]; 16 inline void pushdown(int u){if(rev[u]) rev[ls]^=1,rev[rs]^=1,rev[u]^=1,swap(ls,rs);} 17 inline bool isroot(int u){return c[fa[u]][0]!=u&&c[fa[u]][1]!=u;} 18 inline bool which(int u){return c[fa[u]][1]==u;} 19 void rotate(int u){ 20 int f=fa[u],gf=fa[f],wh=which(u); 21 if(!isroot(f)){c[gf][which(f)]=u;} 22 fa[u]=gf; fa[f]=u; fa[c[u][wh^1]]=f; 23 c[f][wh]=c[u][wh^1]; c[u][wh^1]=f; 24 } 25 void splay(int u){ 26 top=1; q[top]=u; 27 for(int i=u;!isroot(i);i=fa[i]) q[++top]=fa[i]; 28 for(int i=top;i;i--) pushdown(q[i]); 29 while(!isroot(u)){ 30 if(!isroot(fa[u])) rotate(which(u)==which(fa[u])?fa[u]:u); 31 rotate(u); 32 } 33 } 34 void access(int u){for(int son=0;u;son=u,u=fa[u]) splay(u),c[u][1]=son;} 35 void makeroot(int u){ 36 access(u); splay(u); rev[u]^=1; 37 } 38 int find(int u){ 39 access(u); splay(u); 40 while(ls) u=ls; return u; 41 } 42 void split(int x,int y){ 43 makeroot(x); access(y); splay(y); 44 } 45 void cut(int x,int y){ 46 split(x,y); 47 if(c[y][0]==x) c[y][0]=0,fa[x]=0; 48 } 49 void link(int x,int y){ 50 makeroot(x); fa[x]=y; 51 } 52 }t; 53 int main(){ 54 n=read(); m=read(); 55 while(m--){ 56 char c=getchar(); 57 while(c!=‘C‘&&c!=‘D‘&&c!=‘Q‘) c=getchar(); 58 char c2=getchar(); 59 while(c2!=‘ ‘) c2=getchar(); 60 int x=read(),y=read(),xrt=t.find(x),yrt=t.find(y); 61 if(c==‘C‘) if(xrt!=yrt) t.link(x,y); 62 if(c==‘D‘) if(xrt==yrt) t.cut(x,y); 63 if(c==‘Q‘) puts(xrt==yrt?"Yes":"No"); 64 } 65 return 0; 66 }
原文地址:https://www.cnblogs.com/DriverLao/p/8270358.html
时间: 2024-10-12 08:51:48