先做一次dfs求得每个节点为根的子树在树状数组中编号的起始值和结束值,再树状数组做区间查询 与单点更新。
#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<string>
#include<algorithm>
#include<map>
#include<queue>
#include<vector>
#include<cmath>
#include<utility>
using namespace std;
typedef long long LL;
const int N = , INF = 0x3F3F3F3F;
#define MS(a, num) memset(a, num, sizeof(a))
int leftid[N], rightid[N];
struct Node{
int to,next;
}edge[ * N];
int head[N],tot;
void init(){
memset(head, -, sizeof(head));
tot = ;
}
inline void addedge(int u, int to){
edge[tot].to=to;
edge[tot].next=head[u];
head[u]=tot++;
}
int n, m;
bool sta[N];
int C[N];
inline int lowbit(int x){
return x&-x;
}
inline void add(int x, int val){
for(int i=x;i<=n;i+=lowbit(i)){
C[i] += val;
}
}
inline int sum(int x){
int ret = ;
for(int i=x;i>;i-=lowbit(i)){
ret+=C[i];
}
return ret;
} int cnt = ; void dfs(int u, int fa){
leftid[u] = cnt + ;
for(int i = head[u]; ~i ; i = edge[i].next){
int v = edge[i].to;
if(v != fa){
dfs(v, u);
}
}
rightid[u] = ++cnt;
} int main(){
while(~scanf("%d", &n) && n){
MS(C, );
init();
for(int i = ; i <= n; i++){
add(i, );
sta[i] =;
}
int u, v;
for(int i = ; i < n -; i++){
scanf("%d %d", &u, &v);
addedge(u, v);
addedge(v, u);
}
cnt = ;
dfs(, -);
cin>>m;
char ope; while(m--){
scanf(" %c %d", &ope, &u);
int l = leftid[u], r = rightid[u];
if(ope == 'C'){
if(sta[r]){
sta[r] = ;
add(r, -);
}else{
sta[r] = ;
add(r, );
}
}else{
int tp = sum(r) - sum(l - );
printf("%d\n", tp);
}
} }
return ;
}