题目大意:
思路:
算法分析:对于棵树进行
d
f
s
dfs
dfs遍历,并记录每一个点的
d
f
s
dfs
dfs序号
s
t
[
i
]
st[i]
st[i],在一个节点的所有儿子都被遍历过后,记录当前
e
n
[
i
]
en[i]
en[i]为当前最大
d
f
s
dfs
dfs序号的节点的
d
f
s
dfs
dfs序号。
于是,我们把问题转换为将某一点的权值改变,询问区间
[
s
t
[
x
]
,
e
n
[
x
]
]
[st[x], en[x]]
[st[x],en[x]]的和
树状数组可以轻松实现这些操作。
代码:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<queue>
#include<stack>
#include<map>
#include<cstring>
using namespace std;
long long n, m, tot, head[100100], d[100100], st[100100], en[100100];
long long c[100100], a[100100];
struct node
{
long long to, next;
}b[100100];
void VL_ljb(long long x, long long y)
{
b[++tot].to=y;
b[tot].next=head[x];
head[x]=tot;
}
void VL_dfs(long long x)
{
tot++;
st[x]=tot;
for(long long i=head[x]; i; i=b[i].next)
{
VL_dfs(b[i].to);
}
en[x]=tot;
}
long long VL_lowbit(long long x){return x & -x;}
void VL_change(long long x, long long y)
{
for(; x<=n; x+=VL_lowbit(x))
c[x]+=y;
}
long long VL_find(long long x)
{
long long ans=0;
for(; x; x-=VL_lowbit(x))
ans+=c[x];
return ans;
}
int main(){
scanf("%lld", &n);
for(long long i=1; i<n; i++)
{
long long x, y;
scanf("%lld%lld", &x, &y);
VL_ljb(x, y);
}
tot=0;
VL_dfs(1);
for(long long i=1; i<=n; i++)
{
a[i]=1;
VL_change(st[i], 1);
}
scanf("%lld", &m);
for(long long i=1; i<=m; i++)
{
char c;
long long x;
cin>>c;
if(c=='Q')
{
cin>>x;
printf("%lld\n", VL_find(en[x])-VL_find(st[x]-1));
}
else
{
cin>>x;
if(a[x]==0)
{
VL_change(st[x],1);
a[x]=1;
}
else
{
VL_change(st[x], -1);
a[x]=0;
}
}
}
return 0;
}