Title Link: http://poj.org/problem?id=3321
Give you n points, n-1, 1 is the root node. For you m operation, the C operation is to reverse the X point (1 to 0,0 to 1), and the Q operation is to ask for the sum of the X node and the value of its subtree. The initial all nodes are 1.
The DFS-ordered method will iterate through all nodes with 1 as the root node, L[i] represents the earliest timestamp that occurs at point I, R[i] represents the latest timestamp of the I point, and two occurrences per node.
So if you query the sum of the values of I and its subtree, simply query the value between L[i]~r[i] in the tree array and divide by 2, the complexity of log (n). If you change the operation, just change the value on the subscript l[i] and r[i].
Similar topics are HDU3974, but the segment tree is updated and is also written using the Dfs sequence method.
1#include <iostream>2#include <cstring>3#include <cstdio>4#include <vector>5 using namespacestd;6 Const intMAXN = 2e5 +5;7 Const intINF =1e9;8 intHEAD[MAXN], N, M, CNT, L[MAXN], R[MAXN], BIT[MAXN *2], DFN, A[MAXN];9 //a array represents the value of each elementTen structData { One intnext, to; A}EDGE[MAXN *2]; - -InlinevoidAdd_edge (intW Nintv) { theEdge[cnt].next =Head[u]; -Edge[cnt].to =v; -Head[u] = cnt++; - } + - voidDfsintW Nintpar) { +L[u] = + +DFN; A for(inti = Head[u]; ~i; i =Edge[i].next) { at intv =edge[i].to; - if(v = =par) - Continue; - Dfs (v, u); - } -R[u] = + +DFN; in } - toInlinevoidAddintIintx) { + for(; I <= dfn; i + = (I &-i)) -Bit[i] + =x; the } * $ intSuminti) {Panax Notoginseng ints =0; - for(; I >=1; I-= (I &-i)) thes + =Bit[i]; + returns; A } the + intMain () - { $ intu, v; $ Charq[5]; - while(~SCANF ("%d", &N)) { -Memset (Head,-1,sizeof(head)); thememset (bit,0,sizeof(bit)); -Memset (A,0,sizeof(a));WuyiCNT = DFN =0; the for(inti =1; I < n; i++) { -scanf"%d%d", &u, &v); Wu Add_edge (U, v); - Add_edge (V, u); About } $Dfs1, -1); -scanf"%d", &m); - while(m--) { -scanf"%s%d", Q, &u); A if(q[0] =='Q') { +printf"%d\n", ((R[u]-l[u] +1)-(SUM (r[u])-sum (L[u]-1))) /2);//except 2 because each point in the DFS sequence appears 2 times the } - Else { $ if(A[u]) { theAdd (L[u],-1); theAdd (R[u],-1); theA[u] =0; the } - Else { inAdd (L[u],1); theAdd (R[u],1); theA[u] =1; About } the } the } the } +}
POJ 3321 Apple tree (+dfs sequence)