【POJ_3321】Apple Tree
Apple Tree
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
解题思路
我们可以做DFS序,然后就可以**《轻 而 易 举》**地做树状数组了
#include<iostream>
#include<cstdio>
using namespace std;
int n,m,c[100010],d[100010],cnt,v[100010];
int head[100010],tot,tree[100010];
struct abc{
int to,next;
}s[100010];
void add(int x,int y)
{
s[++tot].to=y;
s[tot].next=head[x];
head[x]=tot;
}
void dfs(int x)
{
c[x]=++cnt;
for(int i=head[x];i;i=s[i].next)
dfs(s[i].to);
d[x]=cnt;
}
void find(int x,int y)
{
for(;x<=n;x+=x&(-x))
tree[x]+=y;
}
int ans(int x)
{
int sum=0;
for(;x;x-=x&(-x))
sum+=tree[x];
return sum;
}
int main()
{
cin>>n;
for(int i=1;i<n;i++)
{
int x,y;
scanf("%d%d",&x,&y);
add(x,y);
}
dfs(1);
for(int i=1;i<=n;i++)
{
find(c[i],1);
v[i]=1;
}
cin>>m;
for(int i=1;i<=m;i++)
{
char k;
int t;
cin>>k;
scanf("%d",&t);
if(k=='C')
{
if(v[t]) find(c[t],-1);
else find(c[t],1);
v[t]=1-v[t];
}
else
cout<<ans(d[t])-ans(c[t]-1)<<endl;
}
}
推荐阅读
-
【POJ_3321】Apple Tree
-
树状数组Binary Indexed Tree(1):单点修改,区间查询
-
树状数组Binary Indexed Tree(2):区间修改,单点查询
-
Flatten Binary Tree to Linked List
-
[linux]简单实现的shell中的 tree 命令。 博客分类: linux_app
-
[linux]简单实现的shell中的 tree 命令。 博客分类: linux_app
-
打不开“TS Studio”,因为 Apple 无法检查其是否包含恶意软件。
-
打不开“TS Studio”,因为 Apple 无法检查其是否包含恶意软件。
-
leetcode--minimum-depth-of-binary-tree
-
[Leetcode][python]Minimum Depth of Binary Tree