POJ 3321:apple tree (Dfs sequence + trees array)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.