Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 26762 | Accepted: 7947 |
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
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int ap[],bit[];
int bg[],ed[],cnt=;
int n;
typedef struct{
int to,nxt;
}edge;
edge gra[];
int head[],num=;
int add(int frm,int to){
gra[++num].nxt=head[frm];
gra[num].to=to;
head[frm]=num;
return ;
}
int dfs(int u,int fa){
bg[u]=++cnt;
int j;
for(j=head[u];j;j=gra[j].nxt){
if(gra[j].to!=fa)dfs(gra[j].to,u);
}
ed[u]=cnt;
return ;
}
int lb(int x){
return x&(-x);
}
int c(int x){
int num=ap[x];
x=bg[x];
while(x<=n){
bit[x]+=num;
x+=lb(x);
}
return ;
}
int q(int x){
int a1=,a2=;
int e=ed[x];
while(e){
a1+=bit[e];
e-=lb(e);
}
int b=bg[x]-;
while(b){
a2+=bit[b];
b-=lb(b);
}
return a1-a2;
}
int main(){
scanf("%d",&n);
for(int i=;i<n;i++){
int x,y;
scanf("%d %d",&x,&y);
add(x,y);
add(y,x);
}
dfs(,);
for(int i=;i<=n;i++){
ap[i]=;
c(i);
}
int m;
scanf("%d",&m);
for(int i=;i<=m;i++){
char in[];
int x;
scanf("%s %d",in,&x);
if(in[]=='C'){
ap[x]*=-;
c(x);
}
else printf("%d\n",q(x));
}
return ;
}
睡觉