【POJ_3321】Apple Tree
发布日期:2021-05-06 16:00:33 浏览次数:14 分类:技术文章

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

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

31 21 33Q 1C 2Q 1

Sample Output

32

解题思路

我们可以做DFS序,然后就可以 《轻 而 易 举》 地做树状数组了

#include
#include
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
>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<
<
上一篇:【洛谷_CF261D】Maxim and Increasing Subsequence
下一篇:【SSL_P1502】校门外的树

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2025年03月24日 14时04分04秒