1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
| #include <stdio.h> #include <algorithm> #define il inline #define N 900002 using namespace std;
int n,q,to[N],nx[N],head[N],sze,st[N],f[N]; int F[N],s[N][2],lz[N],t1[N],t2[N],val[N],sum[N];
il void add(int u,int v){to[++sze]=v,nx[sze]=head[u],head[u]=sze;}
il void dfs(int u) { int i,v; for (i=head[u]; i; i=nx[i]) dfs(v=to[i]),sum[u]+=val[v]; if (u<=n) val[u]=sum[u]>1; }
il int ckrt(int x){return s[F[x]][0]==x||s[F[x]][1]==x;}
il void tag(int x,int v){if (x) val[x]=(sum[x]+=v)>1,swap(t1[x],t2[x]),lz[x]+=v;}
il void pushup(int x) { t1[x]=t1[s[x][1]],t2[x]=t2[s[x][1]]; if (!t1[x]) { if (sum[x]!=1) t1[x]=x; else t1[x]=t1[s[x][0]]; } if (!t2[x]) { if (sum[x]!=2) t2[x]=x; else t2[x]=t2[s[x][0]]; } }
il void pushdown(int x) { if (!lz[x]) return; tag(s[x][0],lz[x]),tag(s[x][1],lz[x]),lz[x]=0; }
il void rot(int x) { int y=F[x],z=F[y],k=(s[y][1]==x),w=s[x][!k]; if (ckrt(y)) s[z][s[z][1]==y]=x; s[x][!k]=y,s[y][k]=w; if (w) F[w]=y; F[F[y]=x]=z,pushup(y); }
il void splay(int x) { int y,z=0; for (st[++z]=y=x; ckrt(y); st[++z]=y=F[y]); while (z) pushdown(st[z--]); while (ckrt(x)) { z=F[y=F[x]]; if (ckrt(y)) (s[z][0]==y)^(s[y][0]==x)?rot(x):rot(y); rot(x); } pushup(x); }
il void access(int x){for (int y=0; x; x=F[y=x]) splay(x),s[x][1]=y,pushup(x);}
il int check(int x,int y) { if (x==y) return 0; access(x),splay(x),splay(y); if (s[y][1]==x||s[s[y][1]][1]==x) return 0; access(y),splay(y),splay(x); if (s[x][1]==y||s[s[x][1]][1]==y) return 0; return 1; }
il void upt(int w,int o) { int x=f[w],y,z; access(x),splay(x); if (val[w]) y=t2[x],z=-1; else y=t1[x],z=1; if (y) splay(y),tag(s[y][1],z),pushup(s[y][1]), sum[y]+=z,val[y]=sum[y]>1,pushup(y); else tag(x,z),pushup(x); if (!o) val[w]^=1; }
int main() { scanf("%d",&n); int i,x,y,z,w; for (i=1; i<=n; i++) scanf("%d%d%d",&x,&y,&z), f[x]=f[y]=f[z]=F[x]=F[y]=F[z]=i, add(i,x),add(i,y),add(i,z); for (i=n+1; i<3*n+2; i++) scanf("%d",val+i); dfs(1); for (scanf("%d",&q); q; q--) { scanf("%d%d",&i,&x); if (i==1) upt(x,0); if (i==2) { scanf("%d",&y); if (!check(x,y)) continue; z=f[x],w=f[y]; if (val[x]==val[y]) access(z),splay(x),access(w),splay(y); else upt(x,1),upt(y,1),splay(x),splay(y); f[x]=F[x]=w,f[y]=F[y]=z; } if (i==3) splay(x),printf("%d\n",val[x]); } return 0; }
|