链接
http://poj.org/problem?id=3321
题意
给你一个 n n n个节点的苹果树,开始这颗树上每个结点上都有一个苹果,现在需要你执行 m m m次操作,操作分两种;
- C x C\ x C x,对结点 x x x进行操作,如果结点 x x x处有一个苹果就把它摘下来,如果没有它就重新生长出来一个;
- Q x Q\ x Q x,查询 x x x所在子树苹果个数;
分析
这里考虑使用树状数组+dfs序;
dfs序一般用来将树上的路径问题转化为一维区间问题,如树上莫队等应用;我们使用两个数组 s t 、 e d st、ed st、ed,对于结点 x x x来说,分别代表 d f s dfs dfs的时候第一次经过 x x x和最后一次经过 x x x的时间戳,那么对于 x x x及 x x x子树中任意一结点的时间戳,都在 [ s t [ x ] , e d [ x ] ] [st[x],\ ed[x]] [st[x], ed[x]]之间,那么我们查询 x x x子树的问题就转移到查询区间问题之上了;
之后我们使用树状数组就可以了,需要注意的是我们树状数组的下标是时间戳,对于一个子树,按 d f s dfs dfs得到结点的 s t st st时间戳一定是严格递增的;首先预处理一下,对于任意一个结点 i i i,在 s t [ i ] st[i] st[i]时间戳位置,插入一个1,因为初始的时候树上每个结点都有一个苹果,查询子树 x x x的时候查询 [ s t [ x ] − 1 , e d [ x ] ] [st[x]\ -\ 1,\ ed[x]] [st[x] − 1, ed[x]]即可;对于修改的操作,看它 [ s t [ x ] − 1 , s t [ x ] ] [st[x]\ -\ 1,\ st[x]] [st[x] − 1, st[x]]是否为1,是则插入-1,否则插入1;
还有如果定义 v e c t o r vector vector,定义形式 v e c t o r < v e c t o r < i n t > > v e c ( M A X N ) vector<vector<int> >vec(MAXN) vector<vector<int>>vec(MAXN),需要这样定义,其实链式前向星更好;
代码
#include <functional>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <vector>
#include <queue>
#include <stack>
#include <cmath>
#include <set>
#include <map>
#define INF 0x7f7f7f7f
#define MAXN 100005
#define N 200005
#define P 2
#define MOD 99991
typedef long long ll;
namespace fastIO {
//#define getchar() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1<<22, stdin), p1 == p2) ? EOF : *p1++)
//char buf[(1 << 22)], *p1 = buf, *p2 = buf;
inline int read() {
char c = getchar(); int x = 0, f = 1;
while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); }
while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
}
using namespace fastIO;
using namespace std;
int n, m, st[MAXN], ed[MAXN], tol, c[MAXN];
vector<vector<int> >vec(MAXN);
void insert(int x, int val) {
for (int i = x; i <= n + 2; i += i & -i)
c[i] += val;
}
int sum(int x) {
if (x <= 0)return 0;
int res = 0;
for (int i = x; i > 0; i -= i & -i)
res += c[i];
return res;
}
void dfs(int u) {
st[u] = ++tol;
for (int v = 0; v < vec[u].size(); v++) {
if (st[vec[u][v]])continue;
dfs(vec[u][v]);
}
ed[u] = tol;
}
int main() {
n = read();
int x, y;
for (int i = 1; i <= n - 1; i++) {
x = read(), y = read();
vec[x].push_back(y);
vec[y].push_back(x);
}
dfs(1);
m = read();
char o[2];
for (int i = 1; i <= n; i++)
insert(st[i], 1);
for (int i = 1; i <= m; i++) {
scanf("%s%d", o, &x);
if (o[0] == 'Q') {
printf("%d\n", sum(ed[x]) - sum(st[x] - 1));
}
else if (o[0] == 'C') {
if(sum(st[x]) - sum(st[x] - 1) == 1)
insert(st[x], -1);
else
insert(st[x], 1);
}
}
}