The main idea: the tree for M operations, there are two types of operations, one is to change the weight of a point (0 to 1, 1 to 0), and the other is the root node of the query x is the sum of the sub-tree point weights, starting with a bit of a weight of 1.
Analysis:
The tree is DFS, the tree becomes a sequence, the time stamp of each point in the stack is recorded as the left and right end of its corresponding interval, then its sub-node corresponding interval must be within the interval, the interval sum can be, with a tree-like array to modify and sum.
Code:
ProgramApple;type Point=^node; Node=Recordx:longint; next:point; End;varA:Array[0..100000] ofPoint ; Bit:Array[0..200000] ofLongint; B,V1,V2:Array[0..100000] ofLongint; G:Array[0..100000] ofBoolean; N,i,m,d,x,y:longint; C:char;procedureAdd (x,y:longint);varP:point;beginnew (P); p^.x:=y; P^.NEXT:=A[X]; a[x]:=p;End;procedureDFS (x:longint);varP:point;beginInc (D); V1[x]:=d; G[x]:=true; New (P); p:=A[x]; whileP<>Nil Do begin ifG[p^.x]=false ThenDFS (p^.x); p:=P^.next; End; Inc (d); V2[X]:=D;End;procedureChange (x:longint);varI,y:longint;beginy:=x; ifb[x]=0 Theni:=1 Elsei:=-1; X:=V1[x]; while(x<=2*n) Do beginInc (BIT[X],I); Inc (X,x and(-X));End; B[y]:=1-B[y];End;functionquery (x:longint): Longint;varS:longint;beginS:=0; whileX>0 Do beginInc (S,bit[x]); Dec (x,x and(-X));End; Exit (s);End;beginREADLN (n); fori:=1 toN-1 Do beginreadln (x, y); Add (x, y); Add (y,x); End; D:=0; Dfs1); fori:=1 toN DoChange (i); READLN (m); fori:=1 toM Do beginreadln (c,x); ifC='C' ThenChange (x)ElseWriteln (Query (v2[x])-query (v1[x]-1)); End; End.
View Code
POJ 3321:apple tree (Dfs sequence + trees array)