1 #include<bits/stdc++.h> 2 using namespace std; 3 int fa[500010],ch[500010][2],sum[500010],v[500010],rev[500010],lb[500010],bf[500010][3],n,q,type,ty,last; 4 bool root(int x){ return ((fa[x]==0)or((ch[fa[x]][0]!=x)and(ch[fa[x]][1]!=x))); } 5 bool lch(int x){ return (ch[fa[x]][0]==x); } 6 void up(int x){ sum[x]=sum[ch[x][0]]+v[x]+sum[ch[x][1]]; } 7 void down(int x) 8 { 9 if(rev[x]==0)return; 10 rev[x]=0; swap(ch[x][0],ch[x][1]); if(ch[x][0])rev[ch[x][0]]^=1; if(ch[x][1])rev[ch[x][1]]^=1; 11 } 12 void rot(int x) 13 { 14 if((x==0)or(root(x)))return; 15 int y=fa[x]; int t=fa[y]; 16 if(ch[t][0]==y)ch[t][0]=x;else if(ch[t][1]==y)ch[t][1]=x; fa[x]=t; fa[y]=x; 17 if(ch[y][0]==x){ ch[y][0]=ch[x][1]; if(ch[x][1])fa[ch[x][1]]=y; ch[x][1]=y; } 18 else{ ch[y][1]=ch[x][0]; if(ch[x][0])fa[ch[x][0]]=y; ch[x][0]=y; } 19 up(y); up(x); if(t)up(t); 20 } 21 void splay(int x) 22 { 23 if(x==0)return; int xx=x; int cnt=0; 24 while(!root(xx)){ lb[++cnt]=xx; xx=fa[xx]; } lb[++cnt]=xx; 25 for(int i=cnt;i>=1;i--)down(lb[i]); 26 while(!root(x)){ if(!root(fa[x])){ if((lch(x))^(lch(fa[x])))rot(x);else rot(fa[x]); } rot(x); } 27 } 28 int access(int x) 29 { 30 int t=0; 31 while(x!=0){ splay(x); ch[x][1]=t; up(x); if(t)fa[t]=x; t=x; x=fa[x]; } 32 return t; 33 } 34 void cut(int x,int y) 35 { 36 access(x); int z=access(y); splay(x); 37 if(x==z){ ch[x][1]=0; fa[y]=0; up(x); }else fa[x]=0; 38 } 39 void link(int x,int y) 40 { 41 access(x); splay(x); rev[x]^=1; fa[x]=y; 42 } 43 int qsum(int x,int y) 44 { 45 access(x); int z=access(y); splay(x); 46 if(x==z)return v[x]+sum[ch[x][1]];else return sum[x]+v[z]+sum[ch[z][1]]; 47 }