题目链接:http://poj.org/problem?id=3321
很好的一题
思路,后序遍历求出编号建立树状数组,根节点管理子节点,同时记录子节点个数(DFS),最后树状数组维护区间和
主要是要找出各个节点之间的包含关系
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <vector>
#include <map>
using namespace std;
const int maxn =110000;
map<int,int> ma,nu;
int n,pos,tree[maxn],m,e;
bool rec[maxn];
int head[maxn],vi[maxn];
struct Edge{
int u,v,next;
}edge[maxn*3];
void init(){
memset(head,-1,sizeof(head));
memset(vi,0,sizeof(vi));
e=0;
}
int lowbit(int x){
return x&(-x);
}
void add(int u,int v){
edge[e].u=u,edge[e].v=v,edge[e].next=head[u],head[u]=e++;
edge[e].u=v,edge[e].v=u,edge[e].next=head[v],head[v]=e++;
}
int find_path(int u){
int num=0;
int i,v;
vi[u]=1;
for(int i=head[u];~i;i=edge[i].next){
v=edge[i].v;
if(vi[v]) continue;
num+=find_path(v);
}
tree[pos]=lowbit(pos);
ma[u]=pos++;
nu[u]=num+1;
return num+1;
}
int update(int x,int c){
while(x<pos){
tree[x]+=c;
x+=lowbit(x);
}
return 0;
}
int sum(int x){
int sum=0;
while(x>0){
sum+=tree[x];
x-=lowbit(x);
}
return sum;
}
int main(){
int i,j,k,a,b,t;
char str[3];
while(scanf("%d",&n)!=EOF){
if(n==0) return 0;
init();
ma.clear();
nu.clear();
memset(rec,true,sizeof(rec));
pos=1;
for(i=1;i<n;i++){
scanf("%d%d",&a,&b);
add(a,b);
}
find_path(1);
scanf("%d",&m);
for(i=0;i<m;i++){
scanf("%s %d",str,&a);
t=ma[a];
if(str[0]=='C'){
if(rec[t]){
update(t,-1);
rec[t]=false;
}
else{
update(t,1);
rec[t]=true;
}
}else{
printf("%d\n",sum(t)-sum(t-nu[a]));
}
}
}
return 0;
}