树状数组按dfs序计算。邻接表存树。先深搜一遍整个树,low数组记录开始时间,high记录结束时间。low与high之间为子节点。计算出中间子节点的变化加上原有的数目即可。重点在于dfs来将树形结构映射到树状数组上。
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
#define N 2000005
int n;
int c[N];
int r[N];
int tm, ptr;
struct Node {
int v;
Node *next;
}*head[N], tree[N];
int low[N], high[N];
int lowbit(int x) {
return x& (-x);
}
void init() {
tm = 1;
ptr = 1;
memset(low, 0, sizeof(low));
memset(high, 0, sizeof(high));
memset(head, NULL, sizeof(head));
}
void add(int x, int y) {
tree[ptr].v = y;
tree[ptr].next = head[x];
head[x] = &tree[ptr++];
tree[ptr].v = x;
tree[ptr].next = head[y];
head[y] = &tree[ptr++];
}
void dfs(int rt, int par) {
Node *p = head[rt];
tm++;
low[rt] = tm;
while(p != NULL) {
if(p->v != par) {
dfs(p->v, rt);
}
p = p->next;
}
high[rt] = tm;
}
int Sum(int i) {
int ans = 0;
while(i > 0)
{
ans += c[i];
i -= lowbit(i);
}
return ans;
}
void inst(int i, int del) {
while(i <= tm) {
c[i] += del;
i += lowbit(i);
}
}
int main() {
while(scanf("%d", &n)!=EOF) {
int x, y;
init();
for(int i = 1; i < n; i++) {
scanf("%d%d" , &x, &y);
add(x, y);
}
dfs(1, 1);
for(int i = 1; i <= tm; i++)
r[i] = 1;
int t;
scanf("%d", &t);
char ch[3];
while(t--) {
scanf("%s%d", ch, &x);
if(ch[0] == 'C') {
if(r[x])inst(low[x], -1);
else inst(low[x], 1);
r[x] = 1 - r[x];
}
else {
int ans;
ans = high[x] - low[x] + 1 + Sum(high[x]) - Sum(low[x]-1);
printf("%d\n", ans);
}
}
}
return 0;
}