POJ3321: Apple Tree

Apple Tree
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 9429 Accepted: 2590

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

For every inquiry, output the correspond answer per line.

Sample Input

3
1 2
1 3
3
Q 1
C 2
Q 1

Sample Output

3
2

Source

POJ Monthly--2007.08.05, Huang, Jinsong
 
 
思路:
1、我的第一种思路:因为给出的边顺序未知(后来听oj上的人说蒙了一下,假设第一个是父第二个是子,居然蒙对了),先要逐个记录结点,然后从根开始来一次历遍;给每个结点找到父结点记录起来,每次修改做一次往根部方向的历遍,经过的结点(祖先)都加一(或减一),后来证明操作量太大,不可行;
2、第二种思路:保留了第一种思路里面从根历遍的思路;开始考虑用树状数组来加快查询速度;
3、这个地方如何建树确实是一个关键问题,经过苦思冥想(参考了许多别人的代码,但是老实说,没一个看得懂的,最后我还是靠自己了),写出了函数chck,这个函数在进行历遍的同时把每个结点的管辖范围确定下来
一句话总结这个题:对于n叉树,实现查询的关键在于,使每个结点的管辖范围在树状数组里是连续的,实现连续的方法就是“先子后父”的历遍顺序
举个例子,下面这组数据(只给出结点,可以自己画图看看):
10
1 6
4 1
1 8
2 8
8 7
4 5
4 3
9 4
10 4
0
树状数组对应的结点下标和管辖范围:
 下标:        0         1         2         3         4         5         6         7         8         9         10
 结点:        /          7         2         8         10       9         3         5         4         6          1
 管辖:        /        1~1    2~2     1~3    4~4    4~4    4~4     4~4    4~8     9~9     1~10
POJ测试结果:5328K 454MS 
还不是十分满意,程序还有许多可以优化的地方,用内存偏多,不过搞了很久终于通过,表示现在筋疲力尽暂时不再碰它了 = =|||

 

        

 

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值