BZOJ 3282 Link Cut Tree (LCT)
题目大意:维护一个森林,支持边的断,连,修改某个点的权值,求树链所有点点权的异或和
搞了一个下午终于明白了LCT的原理
1 #include <cstdio> 2 #include <algorithm> 3 #include <cstring> 4 #define root d[0].ch[1] 5 #define il inline 6 #define nu 7777 7 #define inf 500000 8 #define N 300100 9 using namespace std; 10 11 int n,m,tp; 12 int stk[N]; 13 char str[10]; 14 struct Link_Cut_Tree{ 15 int fa[N],ch[N][2],sum[N],val[N],rev[N]; 16 il int idf(int x){return ch[fa[x]][0]==x?0:1;} 17 il int isroot(int x){return (ch[fa[x]][0]!=x&&ch[fa[x]][1]!=x)?1:0;} 18 il void con(int x,int ff,int p){fa[x]=ff;ch[ff][p]=x;} 19 il void pushup(int x){sum[x]=sum[ch[x][0]]^sum[ch[x][1]]^val[x];} 20 il void revers(int x){swap(ch[x][0],ch[x][1]),rev[x]^=1;} 21 il void pushdown(int x){ 22 if(rev[x]){ 23 if(ch[x][0]) revers(ch[x][0]); 24 if(ch[x][1]) revers(ch[x][1]); 25 rev[x]=0;}} 26 il void rot(int x){ 27 int y=fa[x];int ff=fa[y];int px=idf(x);int py=idf(y); 28 if(!isroot(y)) ch[ff][py]=x; 29 fa[x]=ff,con(ch[x][px^1],y,px),con(y,x,px^1); 30 pushup(y),pushup(x);} 31 void splay(int x){ 32 int y=x;stk[++tp]=x; 33 while(!isroot(y)){stk[++tp]=fa[y];y=fa[y];} 34 while(tp){pushdown(stk[tp--]);} 35 while(!isroot(x)){ 36 y=fa[x]; 37 if(isroot(y)) rot(x); 38 else if(idf(y)==idf(x)) rot(y),rot(x); 39 else rot(x),rot(x); 40 }} 41 il void access(int x){for(int y=0;x;y=x,x=fa[x])splay(x),ch[x][1]=y,pushup(x);} 42 il void mkroot(int x){access(x),splay(x),revers(x);} 43 il int findrt(int x){ 44 access(x),splay(x); 45 while(ch[x][0])pushdown(x),x=ch[x][0]; 46 return x;} 47 il void split(int x,int y){mkroot(x),access(y),splay(y);} 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){ 50 mkroot(x); 51 if(findrt(y)==x&&fa[x]==y&&!ch[x][1]) 52 fa[x]=ch[y][0]=0,pushup(y);} 53 }lct; 54 55 int gc() 56 { 57 int rett=0,fh=1;char c=getchar(); 58 while(c<'0'||c>'9'){if(c=='-')fh=-1;c=getchar();} 59 while(c>='0'&&c<='9'){rett=(rett<<3)+(rett<<1)+c-'0';c=getchar();} 60 return rett*fh; 61 } 62 63 int main() 64 { 65 n=gc(),m=gc(); 66 for(int i=1;i<=n;i++) lct.val[i]=gc(); 67 int fl,x,y; 68 for(int i=1;i<=m;i++) 69 { 70 fl=gc(),x=gc(),y=gc(); 71 if(fl==0) lct.split(x,y),printf("%d\n",lct.sum[y]); 72 if(fl==1) lct.link(x,y); 73 if(fl==2) lct.cut(x,y); 74 if(fl==3) lct.splay(x),lct.val[x]=y,lct.pushup(x); 75 } 76 return 0; 77 }