Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 28976 | Accepted: 8597 |
Description
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
Sample Input
3 1 2 1 3 3 Q 1 C 2 Q 1
Sample Output
3 2
题意:一个有n个节点的树,树的每个节点可能有一个苹果或没有,有两种操作:C x 将节点x的权值改变,即如果有一个苹果删掉,否则增加一个苹果。Q x 询问以节点x为根的子树中有多少个苹果。分析:对于这棵树进行dfs遍历,并记录每一个点的dfs序号(p[i]),在一个节点的所有儿子都被遍历过后,记录当前q[i]为当前最大dfs序号的节点的dfs序号,然后就把这棵树转换成了一个数组,然后用树状数组做就行了。代码const maxn=100000; var f:array[0..maxn,0..100] of longint; a,b,c,p,q:array[0..maxn] of longint; x,i,j,n,m,y,num:longint; ch:char; procedure dfs(dep:longint); var i:longint; begin inc(num); p[dep]:=num; for i:=1 to b[dep] do dfs(f[dep,i]); q[dep]:=num; end; procedure insert(x,y:longint); begin while x<=n do begin inc(c[x],y); x:=x+(x and (-x)); end; end; function count(i:longint):longint; var s:longint; begin s:=0; while i>0 do begin s:=s+c[i]; i:=i-(i and (-i)); end; exit(s); end; begin readln(n); for i:=1 to n-1 do begin readln(x,y); inc(b[x]); f[x,b[x]]:=y; end; dfs(1); for i:=1 to n do begin a[i]:=1; insert(i,1); end; readln(m); for i:=1 to m do begin readln(ch,x); if ch='C' then begin a[x]:=-a[x]; insert(p[x],a[x]); end else writeln(count(q[x])-count(p[x]-1)); end; end.