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 toN 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 forku 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 forkx, 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 1Sample Output
3 2 题意:有一棵N个结点的树,初始状态为每个结点处有一个苹果。下面执行M次操作。"C x"表示改变x结点处的状态:若有苹果则摘掉,若没有则加一个苹果。"Q x"表示查询以x为根的子树此时有多少个苹果。 本题显然是单点修改区间查询,故考虑使用树状数组。首先建立图,然后进行dfs记录各点的遍历顺序。在遍历序列中一个结点首次出现到最后出现的区间内的修改操作之和就是以该结点为根的子树的苹果数。 AC代码 #include<iostream> #include<cstring> #include<cstdio> using namespace std; #define maxn 100000+10 int head[maxn],L[maxn],R[maxn],have[maxn],c[2*maxn],t,n; struct edge { int v,next; }e[maxn]; void addedge(int u,int v,int &num) { e[++num].next=head[u];e[num].v=v;head[u]=num; } int lowbit(int x) { return x&(-x); } void add(int x,int val) { while(x<=2*n) { c[x]+=val; x+=lowbit(x); } } int sum(int x) { int ans=0; while(x) { ans+=c[x]; x-=lowbit(x); } return ans; } void dfs(int u) { L[u]=++t;have[u]=1; for(int k=head[u];k!=-1;k=e[k].next) dfs(e[k].v); R[u]=++t; add(L[u],1); } int main() { int tot=0; scanf("%d",&n); memset(head,-1,sizeof(head)); for(int i=1;i<n;i++) { int u,v; scanf("%d%d",&u,&v); addedge(u,v,tot); } t=0;dfs(1); int q;scanf("%d",&q); while(q--) { char ins[5];int x; scanf("%s%d",ins,&x); if(ins[0]=='Q')printf("%d\n",sum(R[x])-sum(L[x]-1)); else { if(have[x]){have[x]=0;add(L[x],-1);} else{have[x]=1;add(L[x],1);} } } }