Description:
There are n nodes on the apple tree. Apple can only grow on the node. One node either has one or no apple. The structure of the tree is provided. One operation is to crop or grow the apple of a node, and the other is to ask how many apples are in the subtree with a node as the root.
Analysis:
The question is very distorted, but can be used.Tree Array.
We set the nodeRenameSo that the number of all child nodes is less than the father's day number, then when you ask how many apples the subtree has in total, it is to ask how many apples the node has smaller than the node number. That is, the tree array model.
Numbering rules: Number the node according to the subsequent Traversal method. The obtained number must be the largest Max in the subtree, and the minimum number min under the node is recorded. Then, after being converted to a tree array model, when querying node v, sum (V. max)-sum (V. min-1) is answered ).
Of course, this question can also be numbered and then usedLine Segment tree.
- /*
- Pku3321 apple tree
- */
- # Include <stdio. h>
- # Include <memory. h>
- # Include <malloc. h>
- # Define CLR (a) memset (A, 0, sizeof ())
- # Define n 100005
- Typedef struct linknode {
- Int ID;
- Struct linknode * next;
- } Link;
- Typedef struct {
- Int index;
- Int min;
- } Index;
- // Vars
- Link mem [N * 2];
- Int pmem;
- Int n, m;
- Link * A [n];
- Int e [N];
- Index idx [N];
- Int nidx;
- Int B [N];
- Int C [N];
- Void addnode (int I, Int J ){
- Link * P = & mem [pmem ++];
- P-> id = J;
- P-> next = A [I];
- A [I] = P;
- }
- Void traversal (INT v ){
- Link * P;
- E [v] = 1;
- Idx [v]. min = nidx;
- P = A [v];
- While (P! = NULL ){
- If (! E [p-> id]) {
- Traversal (p-> ID );
- }
- P = p-> next;
- }
- Idx [v]. Index = nidx ++;
- }
- Int lowbit (int x ){
- Return-X & X;
- }
- Void add (int I, int t ){
- While (I <= N ){
- C [I] + = T;
- I + = lowbit (I );
- }
- }
- Int sum (int I ){
- Int S = 0;
- While (I> 0 ){
- S + = C [I];
- I-= lowbit (I );
- }
- Return S;
- }
- Int main ()
- {
- While (scanf ("% d", & N )! = EOF ){
- Int I, J, K;
- // Input
- CLR (a); pmem = 0;
- For (k = 0; k <n-1; k ++ ){
- Scanf ("% d", & I, & J );
- Addnode (I, j );
- Addnode (J, I );
- }
- // Search Tree
- CLR (E );
- Nidx = 1;
- Traversal (1 );
- // Init tree
- For (k = 1; k <= N; k ++ ){
- B [k] = 1;
- Add (k, 1 );
- }
- // Work
- Char ch [5];
- Int sum;
- Scanf ("% d", & M );
- While (M --){
- Scanf ("% S % d", CH, & K );
- I = idx [K]. index;
- J = idx [K]. min;
- If (CH [0] = 'C') {// change
- B [I] =! B [I];
- Add (I, B [I]? 1:-1 );
- }
- If (CH [0] = 'q') {// inquiry
- Sum = sum (I)-sum (J-1 );
- Printf ("% d/N", sum );
- }
- }
- }
- Return 0;
- }