dfs + 树状数组
单点更新加上区间求和很容易想到线段树, 但是怎么样去构建数据是一个难点,。。开始想了好久也没相同,
其实我们可以做一个映射把无顺序的图映射成一个有序的点阵列, 然后再用树状数组去求
具体的映射就是通过一个DFS, 扫一遍, 这时候需要两个数组STA, END, 分别存放子树的开始节点的序号和结束节点的序号, 而且STA一定是其本身
这样我们的节点序号也有了,子数的范围也有了就可以用树状数组了
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
using namespace std;
#define MAXN 110000
struct Edge
{
int v, next;
}E[MAXN];
int sta[MAXN], end[MAXN];
int num[MAXN];
bool vis[MAXN];
int head[MAXN];
int ecnt = 0, n, cnt;
int getbit( int x)
{
return x&(-x);
}
void change( int pos, int val)
{
while(pos <= n)
{
num[pos] += val;
pos += getbit(pos);
}
}
int getsum( int pos)
{
int res = 0;
while(pos > 0)
{
res += num[pos];
pos -= getbit(pos);
}
return res;
}
void init()
{
ecnt = 0;
memset(head, -1, sizeof(head));
memset(vis, 0, sizeof(vis));
memset(num ,0, sizeof(num));
}
void dfs( int cur)
{
sta[cur] = ++cnt;
for( int i = head[cur]; i != -1; i = E[i].next)
dfs(E[i].v);
end[cur] = cnt;
// cout<<cur <<"--"<<sta[cur] <<" ----- "<<end[cur]<<endl;
}
int main()
{
int a, b, m;
char op;
while(scanf("%d",&n) != EOF)
{
init();
for( int i = 1; i < n ; i++)
{
scanf("%d %d",&a, &b);
E[ecnt].v = b;
E[ecnt].next = head[a];
head[a] = ecnt++;
}
cnt = 0;
dfs(1);
for( int i = 1; i <= n; i++)
change(i, 1);
scanf("%d",&m);
for( int i = 0; i < m; i++)
{ getchar();
scanf("%c%d",&op, &a);
if( op == 'C')
{
if(!vis[a])
{
vis[a] = 1;
change(sta[a], -1);
}
else
{
vis[a] = 0;
change(sta[a], 1);
}
}
else
{
int res = getsum(end[a]) - getsum(sta[a]-1);
printf("%d\n",res);
}
}
}
return 0;
}