dfs 序是一种根据树上 dfs 进出栈顺序将树上节点映射到一维序列映射方法 。映射之后可以用各种数据结构进行维护,从而进行高效的更新查询操作。
如图,左边是一棵树,圆圈内为其节点标号,标号左边为其进出栈序号,右边为维护此树的二叉树,入栈序号即其在原始数组里面的下标。
核心代码:
void dfs(int u, int fa)
{
in[u] = ++time;//当前节点入栈时间
for(int i = head[u]; i != -1; i = edge[i].nex)
{
int v = edge[i].v;
if(fa != v) dfs(v, u);
}
out[u] = time;//出栈时间
}
完整代码
#include <iostream>
#include <cstdio>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define mem(a, b) memset(a, b, sizeof(a))
using namespace std;
const int maxn = 1e5 + 10;
struct node{
int v, nex;
}edge[maxn * 5];
struct Node{
int l, r;
int val;
}tree[maxn * 40];
int n, m;
int head[maxn];
int tot, fa, time;
int in[maxn], out[maxn];
void init()
{
tot = 0;
fa = 0;
mem(out, 0);
mem(in, 0);
time = 0;
mem(tree, 0);
mem(edge, 0);
mem(head, -1);
}
void addedge(int u, int v)
{
edge[tot] = {v, head[u]};
head[u] = tot++;
}
void dfs(int u, int fa)
{
in[u] = ++time;//当前节点入栈时间
for(int i = head[u]; i != -1; i = edge[i].nex)
{
int v = edge[i].v;
if(fa != v) dfs(v, u);
}
out[u] = time;//出栈时间
}
void push_up(int root)
{
tree[root].val = tree[root << 1].val + tree[root << 1 | 1].val;
}
void build(int l, int r, int root)
{
tree[root].l = l, tree[root].r = r;
if(l == r)
{
tree[root].val = 1;
return;
}
int mid = (tree[root].l + tree[root].r) >> 1;
build(l, mid, root << 1);
build(mid + 1, r, root << 1 | 1);
push_up(root);
}
int query(int l, int r, int root)
{
if(tree[root].l >= l && tree[root].r <= r)
return tree[root].val;
int sum = 0;
int mid = (tree[root].l + tree[root].r) >> 1;
if(mid >= l) sum += query(l, r, root << 1);
if(mid + 1 <= r) sum += query(l, r, root << 1 | 1);
return sum;
}
void update(int x, int root)
{
if(tree[root].l == tree[root].r)
{
tree[root].val ^= 1;
return;
}
int mid = (tree[root].l + tree[root].r) >> 1;
if(mid >= x) update(x, root << 1);
else update(x, root << 1 | 1);
push_up(root);
}
int main()
{
int x, y;
scanf("%d", &n);
init();
for(int i = 0; i < n - 1; i++)
{
scanf("%d%d", &x, &y);
addedge(x, y);
addedge(y, x);
}
scanf("%d", &m);
dfs(1, 0);
build(1, n, 1);
for(int i = 0; i < m; i++)
{
char c;
getchar();
scanf("%c", &c);
scanf("%d", &x);
if(c == 'Q')
{
printf("%d\n",query(in[x], out[x], 1)) ;
}
else if(c == 'C')
{
update(in[x], 1);
}
}
return 0;
}