dfs序+树状数组维护;
#include<cstdio>
#include<algorithm>
#define rep(i,k,n) for(int i=k;i<=(n);i++)
using namespace std;
int read(){
int x=0;char ch=getchar();
while(ch<'0'||ch>'9')ch=getchar();
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x;
}
const int N=250005;
struct E{
int to,next;E(int to=0,int next=0):to(to),next(next){}
}edge[2*N];
int head[N],tot=0,n,l[N],r[N],m,tr[2*N],sta[2*N],top=0,cc[N],clock=0;
void add(int x,int y){
edge[++tot]=E(y,head[x]);head[x]=tot;
edge[++tot]=E(x,head[y]);head[y]=tot;
}
void Add(int x,int d){for(;x<=clock;x+=(x&-x))tr[x]+=d;}
int Q(int x){int res=0;for(;x;x-=(x&-x))res+=tr[x];return res;
}
void dfs(){
sta[++top]=1;
while(top){
int u=sta[top];if(!l[u])l[u]=++clock;
for(int i=head[u];i;i=edge[i].next){
int v=edge[i].to;
if(!l[v]){
sta[++top]=v;break;
}
}if(sta[top]==u){
top--;r[u]=++clock;
}
}
}
int main(){//freopen("in.in","r",stdin);
n=read();int x,y;
rep(i,1,n-1){
x=read();y=read();add(x,y);
}dfs();
rep(i,2,n)Add(l[i],1),Add(r[i],-1);
m=read();char s[20];
rep(i,1,n+m-1){
scanf("%s",s);
if(s[0]=='A'){
x=read(),y=read();
Add(l[y],-1),Add(r[y],1);
}
else{x=read();printf("%d\n",Q(l[x]));}
}
}
本文介绍了一种结合DFS序和树状数组的数据结构应用方法,通过实例代码展示了如何使用这两种技术来解决区间查询问题。文章详细解释了DFS遍历过程、树状数组的增删操作及区间查询实现。
263

被折叠的 条评论
为什么被折叠?



