题目链接:http://poj.org/problem?id=3321
乍一看不会做,仔细一看感觉是线段树,但是怎么用线段树做这是一个问题。
对于每个节点先序遍历,求出来每一个节点的管辖区间,然后就是该怎么做就怎么做……单点更新+区间查询,如果求出来取件貌似还比较水,就是那个区间不太好搞定……尤其对于我这种不怎么写深搜的渣渣……应观众要求,还要发一个树状数组版本……
//线段树
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
#define lson l, m, rt << 1
#define rson m + 1, r, rt << 1 | 1
const int maxn = 100100;
int e[maxn], s[maxn], cnt;
bool vis[maxn];
typedef vector<int> INT;
vector<INT> v(maxn);
int sum[maxn << 2];
void PushUp(int rt){
sum[rt] = sum[rt << 1] + sum[rt << 1 | 1];
}
void build(int l, int r, int rt){
sum[rt] = 0;
if (l == r) return;
int m = (l + r) >> 1;
build(lson);
build(rson);
}
void update(int x, int l, int r, int rt){
if (l == r){
sum[rt] = 1 - sum[rt];
return;
}
int m = (l + r) >> 1;
if (x <= m) update(x, lson);
else update(x, rson);
PushUp(rt);
}
int query(int ll, int rr, int l, int r, int rt){
if (ll <= l && rr >= r) return sum[rt];
int m = (l + r) >> 1;
int ret = 0;
if (ll <= m) ret += query(ll, rr, lson);
if (rr > m) ret += query(ll, rr, rson);
return ret;
}
void dfs(int dep){
s[dep] = ++cnt; vis[dep] = 1;
for (int i = 0; i < v[dep].size(); i++){
int u = v[dep][i];
if (!vis[u]) dfs(u);
}
e[dep] = cnt;
return;
}
int main(){
int n, m;
while (~scanf("%d", &n)){
memset(vis, 0, sizeof(vis));
for (int i = 0; i <= n; i++) v[i].clear();
build(1, n, 1);
for (int i = 1; i < n; i++){
int x, y;
scanf("%d%d", &x, &y);
v[x].push_back(y);
v[y].push_back(x);
}
scanf("%d", &m);
cnt = 0; dfs(1);
for (int i = 1; i <= n; i++) update(i, 1, n, 1);
while(m--){
char op[5]; int x;
scanf("%s", op);
if (op[0] == 'Q'){
scanf("%d", &x);
int ans = query(s[x], e[x], 1, n, 1);
printf("%d\n", ans);
}
else{
scanf("%d", &x);
update(s[x], 1, n, 1);
}
}
}
return 0;
}
//树状数组
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
const int maxn = 100100;
int e[maxn], s[maxn], cnt, n;
bool vis[maxn];
typedef vector<int> INT;
vector<INT> v(maxn);
int a[maxn], c[maxn];
int lowbit(int x){return x & (-x);}
void update(int x){
a[x] = 1 - a[x];
int d = a[x] ? 1 : -1;
while (x <= n){
c[x] += d; x += lowbit(x);
}
}
int getsum(int x){
int ret = 0;
while (x > 0){
ret += c[x]; x -= lowbit(x);
}
return ret;
}
void dfs(int dep){
s[dep] = ++cnt; vis[dep] = 1;
for (int i = 0; i < v[dep].size(); i++){
int u = v[dep][i];
if (!vis[u]) dfs(u);
}
e[dep] = cnt;
return;
}
int main(){
int m;
while (~scanf("%d", &n)){
memset(vis, 0, sizeof(vis));
memset(c, 0, sizeof(c));
memset(a, 0, sizeof(a));
for (int i = 0; i <= n; i++) v[i].clear();
for (int i = 1; i < n; i++){
int x, y;
scanf("%d%d", &x, &y);
v[x].push_back(y);
v[y].push_back(x);
}
scanf("%d", &m);
cnt = 0; dfs(1);
for (int i = 1; i <= n; i++) update(i);
while(m--){
char op[5]; int x;
scanf("%s", op);
if (op[0] == 'Q'){
scanf("%d", &x);
int ans = getsum(e[x]) - getsum(s[x] - 1);
printf("%d\n", ans);
}
else{
scanf("%d", &x);
update(s[x]);
}
}
}
return 0;
}