题目:
There is an apple tree outside of kaka’s house. Every autumn, a lot of apples will grow in the tree. Kaka likes apple very much, so he has been carefully nurturing the big apple tree.
The tree has N forks which are connected by branches. Kaka numbers the forks by 1 to N and the root is always numbered by 1. Apples will grow on the forks and two apple won’t grow on the same fork. kaka wants to know how many apples are there in a sub-tree, for his study of the produce ability of the apple tree.
The trouble is that a new apple may grow on an empty fork some time and kaka may pick an apple from the tree for his dessert. Can you help kaka?
InPut
The first line contains an integer N (N ≤ 100,000) , which is the number of the forks in the tree.
The following N - 1 lines each contain two integers u and v, which means fork u and fork v are connected by a branch.
The next line contains an integer M (M ≤ 100,000).
The following M lines each contain a message which is either
“C *x*“ which means the existence of the apple on fork x has been changed. i.e. if there is an apple on the fork, then Kaka pick it; otherwise a new apple has grown on the empty fork.
or
“Q *x*“ which means an inquiry for the number of apples in the sub-tree above the fork x, including the apple (if exists) on the fork x
Note the tree is full of apples at the beginning
OutPut
For every inquiry, output the correspond answer per line.
Sample input
1 | 3 |
Sample output
1 | 3 |
解析
题意:有一颗苹果树,一开始每个节点都有一个苹果,之后有俩种操作:1)摘下一个苹果或者在空结点长出一个新苹果;2)查询以x为根节点的子树的权值和。
第一个操作就是该节点的权值发生改变:1🠖0:摘下一个苹果;0🠖1:长出新苹果;
第二操作就是求一个权值和。
因为这个苹果树变化较频繁而且要求权值和,用遍历不是很好,所以引入树状数组$c[]$,以访问时间为顺序,在后后续遍历过程中以时间的形式变为线性结构。
1.设:
$d[u]$为节点的初始访问时间
$f[u]$为节点的结束访问时间(从它的子树回溯回来的时间)
$[d[u],f[u]]$就是以$u$为根的子树的结构,若$[d[v],f[v]]$是$[d[u],f[u]]$的子区间,则以$u$为根节点的树包含了以$v$为根节点的子树。在代码中用DFS来计算这个区间
2.若为第一个操作即 $C x$,也就是节点的权值发生变化,则$a[f[x]]=(a[f[x]]+1)\%2$,并从$c[f[x]]$出发调整树状数组$c[]$。在代码中用change
3.若为第二个操作即$Qx$,则以节点x为根节点的权值和为$sum(f[x])-sum(d[x]-1)$,其中$sum[x]$为前$x$个访问时间的前缀和。
完整代码
1 |
|