POJ3321 Apple Tree(树状数组 + dfs + 线性表)

来源:互联网 发布:淘宝网男童运动套装 编辑:程序博客网 时间:2024/05/16 05:46

Apple Tree
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 21885 Accepted: 6634

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
"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
"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 - 1条熟知,m次询问,若为Q,问你树叉x上共有多少苹果树,若为C,树叉x有苹果树则摘掉,没有则

长出一个。


首先用链表存储每个树叉的信息,然后dfs扫一次将信息保存到两个数组st, ed中,最后使用树状数组即可。


AC代码:


#include "iostream"#include "cstdio"#include "cstring"#include "algorithm"using namespace std;const int MAXN = 1e5 + 5;int n, m, c[MAXN], st[MAXN], ed[MAXN], num;struct node{/* data */int data;node *next;}t[MAXN];void dfs(int x){st[x] = ++num;node *p = t[x].next;while(p) {if(st[p -> data] == 0) dfs(p -> data);p = p -> next;}ed[x] = num;}int lobbit(int x){return x & (-x);}void update(int x, int v){for(int i = x; i <= n; i += lobbit(i))c[i] += v;}int get_sum(int x){int sum = 0;for(int i = x; i > 0; i -= lobbit(i))sum += c[i];return sum;}int main(int argc, char const *argv[]){while(scanf("%d", &n) != EOF) {num = 0;memset(c, 0, sizeof(c));for(int i = 1; i < n; ++i) {int u, v;scanf("%d%d", &u, &v);node *p = new node;p -> data = v;p -> next = t[u].next;t[u].next = p;node *q = new node;q -> data = u;q -> next = t[v].next;t[v].next = q;}dfs(1);for(int i = 1; i <= n; ++i)update(i, 1);scanf("%d", &m);for(int i = 0; i < m; ++i) {char op[2];int x;scanf("%s%d", op, &x);if(op[0] == 'C') {int tmp = get_sum(st[x]);tmp -= get_sum(st[x] - 1);if(tmp == 1) update(st[x], -1);else update(st[x], 1);}else {int ans = get_sum(ed[x]);ans -= get_sum(st[x] - 1);printf("%d\n", ans);}}}return 0;}


1 0
原创粉丝点击