POJ3321 Apple Tree
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 26989 | Accepted: 8004 |
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
Sample Input
3
1 2
1 3
3
Q 1
C 2
Q 1
Sample Output
3
2
Source
1 /**/ 2 #include<iostream> 3 #include<cstdio> 4 #include<cmath> 5 #include<cstring> 6 #include<algorithm> 7 using namespace std; 8 const int mxn=400020; 9 struct edge{ 10 int v,next; 11 }e[mxn]; 12 int hd[mxn],mcnt=0; 13 void add_edge(int u,int v){ 14 e[++mcnt].next=hd[u];e[mcnt].v=v;hd[u]=mcnt; 15 return; 16 } 17 int n,m; 18 int t[mxn]; 19 bool f[mxn]; 20 int lowbit(int x){return x&-x;} 21 void add(int p,int v){ 22 while(p<mxn){t[p]+=v;p+=lowbit(p);} 23 } 24 int ask(int p){ 25 int res=0; 26 while(p){res+=t[p];p-=lowbit(p);} 27 return res; 28 } 29 int in[mxn],out[mxn]; 30 int cnt=0; 31 void dfs(int u,int fa){ 32 in[u]=++cnt; 33 for(int i=hd[u];i;i=e[i].next){ 34 int v=e[i].v; 35 if(v==fa)continue; 36 dfs(v,u); 37 } 38 out[u]=++cnt; 39 return; 40 } 41 int main(){ 42 scanf("%d",&n); 43 int i,j; 44 int u,v; 45 for(i=1;i<n;i++){ 46 scanf("%d%d",&u,&v); 47 add_edge(u,v); 48 add_edge(v,u); 49 } 50 dfs(1,0); 51 for(i=1;i<=n;i++){ 52 f[i]=1; 53 add(in[i],1); 54 } 55 scanf("%d",&m); 56 char ch[2]; 57 for(i=1;i<=m;i++){ 58 scanf("%s%d",ch,&u); 59 if(ch[0]=='Q') 60 printf("%d\n",ask(out[u])-ask(in[u]-1)); 61 else{ 62 if(f[u]){ 63 f[u]=0; 64 add(in[u],-1); 65 } 66 else{ 67 f[u]=1; 68 add(in[u],1); 69 } 70 } 71 } 72 return 0; 73 }