POJ-3321
大佬的博客
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
#define ll long long
const int maxn = 1e5 + 10;
int n, trans[maxn];
//避免超时,用了vector + vector;不能用vector<maxn>
vector<vector<int> > v(maxn);
int tree[maxn];
int apple[maxn];
int Next[maxn];
int cnt = 1;
inline int lowbit(int x) { return x&(-x); }
void add(int x, int num) { for (int i = x; i <= n; i += lowbit(i)) tree[i] += num; }
ll getsum(int x) {
ll ans = 0;
for (int i = x; i > 0; i -= lowbit(i)) ans += tree[i];
return ans;
}
void dfs(int x) {
trans[x] = cnt++;
for (int i = 0; i < v[x].size(); i++) dfs(v[x][i]);
Next[trans[x]] = cnt - 1;
}
int main() {
//freopen("in","r",stdin);
while (scanf("%d", &n) !=EOF && n) {
int a, b;
cnt = 1;
memset(tree, 0, sizeof(tree));
memset(Next, 0, sizeof(Next));
memset(trans, 0, sizeof(trans));
for (int i = 1; i <= n; i++) {
v[i].clear();
apple[i] = 1;
add(i, 1);
}
for (int i = 1; i < n; i++) {
scanf("%d %d", &a, &b);
v[a].push_back(b);
}
dfs(1);
int T;
scanf("%d", &T);
while (T--) {
char s[4];
int k;
scanf("%s %d",s,&k);
int t = trans[k];
if (s[0] == 'Q') {
ll t1 = getsum(Next[t]);
ll t2 = getsum(t - 1);
printf("%lld
", getsum(Next[t]) - getsum(t - 1));
} else {
if (apple[k] == 1)
add(t, -1);
else add(t, 1);
apple[k] = !apple[k];
}
}
}
return 0;
}