Test Instructions: Give you a tree of n points, n-1 no edge, initially each node is 1, and now there are two operations, one is to the value of a node or 1, one is to find the current node and its subordinate nodes of the value of the.
Method: Converts a tree array.
parsing: How do I convert a tree array? Is the application of the search order to convert. This approach is used because the tree array maintains a linear, and this problem happens to be mapped to linear using the search order. Can give an example to illustrate
As shown in the tree, we search for it at the time 1 is the first to be traversed, and only after all the points are traversed and then back to 1, so 1 of the search order can be seen with the starting endpoint and end point is [1,5] to represent, similarly, 2 of the beginning of 2, the end of 4,[2,4] to represent 2, 4 you can use [3,3],5 [4,4],3] with [5,5], so that the tree is projected to linear, and then the tree-like array is very simple.
Code:
#include <stdio.h>#include <string.h>structnode{intto;intNext;};BOOLis_used[100001]; node edge[100001*2] ;inthead[100001] ;Charuseless[5] ;ints[100001] ;inte[100001] ;intc[100001] ;intindex;intCNT;intn;voidInit () {memset(Head,-1,sizeof(head)) ; CNT =1;}voidEdgeadd (intFrom,intTo) {edge[cnt].to = to; Edge[cnt].next = Head[from]; Head[from] = cnt++;}voidDfsintFA,inttoo) {S[too] = ++index; for(inti = Head[too]; I! =-1; i = edge[i].next) {intto = edge[i].to;if(To! = FA) {DFS (too, to); }} E[too] = index;}intLowbit (intx) {returnX & (-X);}voidUpdata (intXintTMP) { while(x <= N) {C[x] + = tmp; x + = Lowbit (x); }}intGetsum (intx) {intsum =0; while(x) {sum + = c[x]; X-= Lowbit (x); }returnsum;}intMain () {scanf("%d", &n); Init (); for(inti =1; I < n; i++) {intx, y;scanf("%d%d", &x, &y); Edgeadd (x, y); Edgeadd (y, x); } DFS (-1,1) ; for(inti =1; I <= N; i++) {Updata (I,1) ; Is_used[i] =1; }intQ;scanf("%d", &q); for(inti =1; I <= Q; i++) {scanf('%s ', useless);if(useless[0] ==' C ') {intx;scanf("%d", &x);if(Is_used[x] = =1) {Is_used[x] =0; Updata (S[x],-1) ; }Else{Is_used[x] =1; Updata (S[x],1) ; } }Else{intx;scanf("%d", &x);printf("%d\n", Getsum (E[x])-Getsum (S[x]-1)) ; } }}
POJ 3321 Apple Tree Tree Array