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?
![](https://i-blog.csdnimg.cn/blog_migrate/95a992a75f75b7d92488d79284d3b4ef.gif)
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
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
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
树状数组~但不是裸的~
对于每一个点记录le[ ]和ri[ ],dfs一遍就可以记录了,然后每次要求的就是getnum(ri[x])-getnum(le[x]-1) ~
然后,记录每个节点是否有苹果的数组和树状数组要分清!弄混了的我悲伤地检查了两个小时……
#include<cstdio>
#include<cstring>
#include<vector>
using namespace std;
int a[100005],n,m,le[100005],ri[100005],x,y,now,c[100005];
vector<vector<int> > ro(100005);
char s[6];
int lowbit(int u)
{
return u&(-u);
}
void add(int u,int v)
{
for(int j=u;j<=n;j+=lowbit(j)) a[j]+=v;
}
int getnum(int u)
{
int ans=0;
for(int j=u;j;j-=lowbit(j)) ans+=a[j];
return ans;
}
void dfs(int u)
{
le[u]=now;
for(int i=0;i<ro[u].size();i++)
{
now++;dfs(ro[u][i]);
}
ri[u]=now;
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n-1;i++)
{
scanf("%d%d",&x,&y);
ro[x].push_back(y);
}
now=1;dfs(1);
for(int i=1;i<=n;i++)
{
c[i]=1;add(i,1);
}
scanf("%d",&m);
while(m--)
{
scanf("%s%d",s,&x);
if(s[0]=='Q') printf("%d\n",getnum(ri[x])-getnum(le[x]-1));
else
{
if(c[x]) add(le[x],-1);
else add(le[x],1);
c[x]=!c[x];
}
}
return 0;
}