博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
POJ3321 Apple Tree (树状数组)
阅读量:6535 次
发布时间:2019-06-24

本文共 2670 字,大约阅读时间需要 8 分钟。

Apple Tree
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 16180   Accepted: 4836

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

31 21 33Q 1C 2Q 1

Sample Output

32 题目大意级是说,给你一颗树,最初每个节点上都有一个苹果,有两种操作:修改(即修改某一个节点,修改时这一个节点苹果从有到无,或从无到有)和查询(查询某一个节点他的子树上有多少个苹果)。 由于此题数据比较大(N<=10^5),而且不是标准的二叉树,所以这里我们队每一个节点重新编号,另外为每一个节点赋一个左值和一个右值,表示这个节点的管辖范围。

上图也就是DFS搜索的时候做标记的过程,这样新的编号为1~6的节点所管辖的范围分别就是[1,6]  [2,4]   [3,3]  [4,4]  [5,6]  [6,6],其中左边的是左值,右边的是右值,节点1的区间是[1,6],正好这棵子树有6个节点,其他也一样 那我们吧新的节点放进树状数组时

那我们求出每一个节点从1~左值的和  和  1~右值的和  他们的差就是这个节点的子树的所有的和(即这棵子树苹果数目)

可以百度下看看树状数组的实现

最后每输入一组数据就进行依次操作就可以了

1 #include 
2 #include
3 #include
4 #define MAXN 100005 5 #define mem(a) memset(a, 0, sizeof(a)) 6 using namespace std; 7 8 int TreeArray[MAXN], Left[MAXN], Right[MAXN], Fork[MAXN]; 9 typedef vector
Ve;10 vector
Edge(MAXN);11 int N,M;12 int key;13 14 void init()//初始化数组和15 {16 mem(Left); mem(Right);17 mem(Fork); mem(TreeArray);18 for(int i=0;i
=1)50 {51 sum += TreeArray[k];52 k -= LowBit(k);53 }54 return sum;55 }56 57 void ReadDataAndDo()58 {59 int a,b;60 char ch;61 for(int i=1;i

 

 

转载于:https://www.cnblogs.com/gj-Acit/p/3236843.html

你可能感兴趣的文章