裸树链剖分。根据dfs序确定子树在线段树上的区间范围。对于install操作,答案即该节点深度 - 该点到根节点的链上已安装的个数,然后将该链全部赋值为已安装。对于unistall操作,答案即子树已安装个数,然后将子树赋值为未安装。
#include <vector>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 100100;
vector<int> E[N];
int size[N], dep[N], fa[N], son[N], top[N];
void dfs1(int u, int f, int d) {
size[u] = 1; son[u] = -1, fa[u] = f, dep[u] = d;
int tmp = 0;
for (int i = 0; i < E[u].size(); i++) {
int &v = E[u][i];
dfs1(v, u, d + 1);
if (size[v] > tmp) {
tmp = size[v];
son[u] = v;
}
size[u] += size[v];
}
}
int innu[N], outnu[N], treenu[N], segCnt = 0;
void dfs2(int u, int tp) {
top[u] = tp;
treenu[innu[u] = ++segCnt] = u;
if (son[u] == -1) {
outnu[u] = segCnt;
return;
}
dfs2(son[u], tp);
for (int i = 0; i < E[u].size(); i++) {
int &v = E[u][i];
if (son[u] == v) continue;
dfs2(v, v);
}
outnu[u] = segCnt;
}
int sum[N<<1], mark[N<<1], lz[N<<1];
#define g(l, r) (l + r | l != r)
#define o g(l, r)
#define ls g(l, mid)
#define rs g(mid + 1, r)
int gl, gr, gx;
inline void initTree() {
dfs1(0, -1, 1); dfs2(0, 0);
memset(mark, 0xff, sizeof(mark));
}
inline void push(int l, int r) {
if (mark[o] == -1) return;
int mid = l + r >> 1;
if (l < r) {
mark[ls] = mark[o];
sum[ls] = mark[o] * (mid - l + 1);
mark[rs] = mark[o];
sum[rs] = mark[o] * (r - (mid + 1) + 1);
}
mark[o] = -1;
}
inline void update(int l, int r) {
int mid = l + r >> 1;
sum[o] = sum[ls] + sum[rs];
}
int getSum(int l, int r) {
if (gl <= l && r <= gr) {
return sum[o];
}
push(l, r);
int mid = l + r >> 1, ans = 0;
if (gl <= mid) ans += getSum(l, mid);
if (gr >= mid + 1) ans += getSum(mid + 1, r);
return ans;
}
inline int __getSum(int l, int r) {
gl = l, gr = r;
return getSum(1, segCnt);
}
void modify(int l, int r) {
if (gl <= l && r <= gr) {
sum[o] = gx * (r - l + 1);
mark[o] = gx;
return;
}
push(l, r);
int mid = l + r >> 1;
if (gl <= mid) modify(l, mid);
if (gr >= mid + 1) modify(mid + 1, r);
update(l, r);
}
inline void __modify(int l, int r, int x) {
gl = l, gr = r, gx = x;
modify(1, segCnt);
}
inline void install(int u) {
int f = top[u], ans = dep[u];
while (f != 0) {
ans -= __getSum(innu[f], innu[u]);
__modify(innu[f], innu[u], 1);
u = fa[f]; f = top[u];
}
ans -= __getSum(innu[0], innu[u]);
__modify(innu[0], innu[u], 1);
printf("%d\n", ans);
}
inline void unistall(int u) {
int ans = __getSum(innu[u], outnu[u]);
__modify(innu[u], outnu[u], 0);
printf("%d\n", ans);
}
int n, q;
char cs[15];
int main() {
cin >> n;
for (int i = 1; i < n; i++) {
int tmp; scanf("%d", &tmp);
E[tmp].push_back(i);
} cin >> q;
initTree();
while (q--) {
int tmp;
scanf("%s%d", cs, &tmp);
if (*cs == 'i') install(tmp);
else unistall(tmp);
}
return 0;
}