Apple Tree_poj3321_树状数组&dfs

来源:互联网 发布:噩梦 知乎 编辑:程序博客网 时间:2024/05/17 00:00

Description

There is an apple tree outside of kaka'shouse. Every autumn, a lot of apples will grow in the tree. Kaka likes applevery much, so he has been carefully nurturing the big apple tree.

The tree has N forks which areconnected by branches. Kaka numbers the forks by 1 to N and the rootis always numbered by 1. Apples will grow on the forks and two apple won't growon 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 onan empty fork some time and kaka may pick an apple from the tree for hisdessert. 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 hasbeen 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 thesub-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 correspondanswer per line.

Sample Input

3

1 2

1 3

3

Q 1

C 2

Q 1

Sample Output

3

2

题目大意:

一个有n个节点的树,树的每个节点可能有一个苹果或没有,有两种操作:

       Cx 将节点x的权值改变,即如果有一个苹果删掉,否则增加一个苹果。

       Qx 询问以节点x为根的子树中有多少个苹果。

       数据范围:1 <= n <= 100000, 询问个数m <= 100000

思路:

线段树?别逗。对于棵树进行dfs遍历,并记录每一个点的dfs序号(s[i]),在一个节点的所有儿子都被遍历过后,记录当前e[i]为当前最大dfs序号的节点的dfs序号。

将一棵树的子树映射到了一个区间。问题转化为了区间操作

C x 将某一点的权值改变

Q x 询问区间[s[x], e[x]]的和

树状数组可以轻松实现这些操作。

值得注意的是,提交程序时因为数组过大MLE爆内存,最后发现不用开太大也能过,满页都是红色的TLE也是蛋疼。

 

源代码/pas:

var  f,s,e,b:array[0..100000]of longint;  t:array[0..100000,0..100]of longint;  n,dep:longint;function get(x:longint):longint;begin  get:=0;  while x>0 do  begin    get:=get+f[x];    x:=x-(x and(-x));  end;end;procedure add(x,y:longint);begin  while x<=n do  begin    f[x]:=f[x]+y;    x:=x+(x and(-x));  end;end;procedure dfs(x:longint);var  i:longint;begin  inc(dep);  s[x]:=dep;  for i:=1 to t[x,0] do  dfs(t[x,i]);  e[x]:=dep;end;procedure init;var  x,y,i:longint;begin  readln(n);  for i:=1 to n-1 do  begin    readln(x,y);    inc(t[x,0]);    t[x,t[x,0]]:=y;  end;end;procedure main;var  m,i,x:longint;  c:char;begin  for i:=1 to n do  begin    b[i]:=1;    add(i,b[i]);  end;  dfs(1);  readln(m);  for i:=1 to m do  begin    readln(c,x);    case c of      'Q':writeln(get(e[x])-get(s[x]-1));      'C':      begin        b[x]:=b[x]*-1;        add(s[x],b[x]);      end;    end;  end;end;begin  init;  main;end.


0 0
原创粉丝点击