【链接】
bzoj1103
【解题报告】
DFS序+树状数组(或线段树)
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=250005,maxm=500005;
int n,m,tot,Time,c[maxm],lnk[maxn],son[maxm],nxt[maxm],in[maxn],out[maxn],fa[maxn];
inline char nc()
{
static char buf[100000],*l,*r;
if (l==r) r=(l=buf)+fread(buf,1,100000,stdin);
if (l==r) return EOF; return *l++;
}
inline int Read()
{
int res=0,f=1; char ch=nc(),cc=ch;
while (ch<'0'||ch>'9') cc=ch,ch=nc();
if (cc=='-') f=-1;
while (ch>='0'&&ch<='9') res=res*10+ch-48,ch=nc();
return res*f;
}
void Add(int x,int y) {son[++tot]=y; nxt[tot]=lnk[x]; lnk[x]=tot;}
void Dfs(int x,int Fa)
{
in[x]=++Time; fa[x]=Fa;
for (int j=lnk[x]; j; j=nxt[j])
if (son[j]!=Fa) Dfs(son[j],x);
out[x]=++Time;
}
int Lowbit(int x) {return x&(-x);}
void AddT(int x,int da) {while (x<=2*n) c[x]+=da,x+=Lowbit(x);}
int GetT(int x) {int sum=0; while (x) sum+=c[x],x-=Lowbit(x); return sum;}
int main()
{
freopen("1103.in","r",stdin);
freopen("1103.out","w",stdout);
n=Read(); tot=Time=0;
memset(lnk,0,sizeof(lnk));
for (int i=1,x,y; i<n; i++) x=Read(),y=Read(),Add(x,y),Add(y,x);
Dfs(1,0);
memset(c,0,sizeof(c));
for (int i=1; i<=n; i++) AddT(in[i],1),AddT(out[i],-1);
m=Read();
for (int i=1; i<n+m; i++)
{
char ch=nc(); int x,y;
while (ch!='W'&&ch!='A') ch=nc();
if (ch=='W') x=Read(),printf("%d\n",GetT(in[x])-1);
else x=Read(),y=Read(),AddT(in[y],-1),AddT(out[y],1);
}
return 0;
}