BZOJ 2049 [SDOI2008]洞穴勘测 (LCT)
题目大意:维护一个森林,支持边的断,连,以及查询连通性
LCT裸题 洛谷P2147传送门
1A了,给自己鼓鼓掌
1 #include <cstdio> 2 #include <algorithm> 3 #include <cstring> 4 #define il inline 5 #define inf 500000 6 #define N 10100 7 using namespace std; 8 9 int n,m,tp; 10 int stk[N]; 11 struct LinkCutTree{ 12 int fa[N],ch[N][2],rv[N]; 13 il int idf(int x){return ch[fa[x]][0]==x?0:1;} 14 il void con(int x,int ff,int p){fa[x]=ff,ch[ff][p]=x;} 15 il int isroot(int x){return (ch[fa[x]][0]!=x&&ch[fa[x]][1]!=x)?1:0;} 16 il void rev(int x){swap(ch[x][0],ch[x][1]),rv[x]^=1;} 17 il void pushdown(int x) 18 { 19 if(!rv[x]) return; 20 if(ch[x][0]) rev(ch[x][0]); 21 if(ch[x][1]) rev(ch[x][1]); 22 rv[x]=0; 23 } 24 il void rot(int x) 25 { 26 int y=fa[x];int ff=fa[y];int px=idf(x);int py=idf(y); 27 if(!isroot(y)) ch[ff][py]=x; 28 fa[x]=ff;con(ch[x][px^1],y,px),con(y,x,px^1); 29 //pushup(y),pushup(x); 30 } 31 void splay(int x) 32 { 33 int y=x;stk[++tp]=x; 34 while(!isroot(y)){stk[++tp]=fa[y],y=fa[y];} 35 while(tp){pushdown(stk[tp--]);} 36 while(!isroot(x)) 37 { 38 y=fa[x]; 39 if(isroot(y)) rot(x); 40 else if(idf(y)==idf(x)) rot(y),rot(x); 41 else rot(x),rot(x); 42 } 43 } 44 void access(int x){for(int y=0;x;y=x,x=fa[x])splay(x),ch[x][1]=y;/*pushup(x)*/} 45 il void mkroot(int x){access(x),splay(x),rev(x);} 46 il void split(int x,int y){mkroot(x),access(y),splay(y);} 47 int findrt(int x){access(x),splay(x);while(ch[x][0])pushdown(x),x=ch[x][0];return x;} 48 il void link(int x,int y){mkroot(x);if(findrt(y)!=x)fa[x]=y;} 49 il void cut(int x,int y){mkroot(x);if(findrt(y)==x&&fa[x]==y&&!ch[x][1])fa[x]=ch[y][0]=0;/*pushup(y)*/} 50 }lct; 51 int gint() 52 { 53 int rett=0,fh=1;char c=getchar(); 54 while(c<'0'||c>'9'){if(c=='-')fh=-1;c=getchar();} 55 while(c>='0'&&c<='9'){rett=(rett<<3)+(rett<<1)+c-'0';c=getchar();} 56 return rett*fh; 57 } 58 59 int main() 60 { 61 n=gint(),m=gint(); 62 int fl,x,y;char str[20]; 63 for(int i=1;i<=m;i++) 64 { 65 scanf("%s",str); 66 x=gint(),y=gint(); 67 if(str[0]=='C'){lct.link(x,y);} 68 if(str[0]=='D'){lct.cut(x,y);} 69 if(str[0]=='Q'){ 70 if(lct.findrt(x)==lct.findrt(y)) 71 printf("Yes\n"); 72 else printf("No\n");} 73 } 74 return 0; 75 }