调一下代码:
#include<bits/stdc++.h>
using namespace std;
int n, q, tim, cnt;
vector<int> v[100010];
int siz[100010], ft[100010], dep[100010], son[100010], dfn[100010], bl[100010], top[100010];
int sum[400010], add[400010], tl[400010], tr[400010];
void dfs1(int x, int fa){
siz[x] = 1;
ft[x] = fa;
dep[x] = dep[fa] + 1;
int maxn = 0, maxm = -1;
for(auto i : v[x]){
if(i == fa) continue;
dfs1(i, x);
siz[x] += siz[i];
if(siz[i] > maxn){
maxn = siz[i];
maxm = i;
}
}
son[x] = maxm;
}
void dfs2(int x, int fa, int tp){
dfn[x] = ++ tim;
bl[x] = tp;
if(son[x] != -1) dfs2(son[x], x, tp);
for(auto i : v[x]){
if(i == fa) continue;
if(i != son[x]){
top[++ cnt] = i;
dfs2(i, x, cnt);
}
}
}
void downdata(int bh){
if(add[bh] == -1) return;
add[bh << 1] = add[bh];
add[bh << 1 | 1] = add[bh];
sum[bh << 1] = (tr[bh << 1] - tl[bh << 1] + 1) * add[bh];
sum[bh << 1 | 1] = (tr[bh << 1 | 1] - tl[bh << 1 | 1] + 1) * add[bh];
add[bh] = -1;
}
void updata(int bh){
sum[bh] = sum[bh << 1] + sum[bh << 1 | 1];
}
void build(int bh, int l, int r){
tl[bh] = l, tr[bh] = r, add[bh] = -1;
if(l == r){
sum[bh] = 0;
return;
}
int mid = (l + r) >> 1;
build(bh << 1, l, mid);
build(bh << 1 | 1, mid + 1, r);
updata(bh);
}
void modifiy(int bh, int l, int r, int d){
if(r < tl[bh] || l > tr[bh]) return;
if(tl[bh] >= l && tr[bh] <= r){
add[bh] = d;
sum[bh] = (tr[bh] - tl[bh] + 1) * d;
return;
}
downdata(bh);
modifiy(bh << 1, l, r, d);
modifiy(bh << 1 | 1, l, r, d);
updata(bh);
}
int query_sum(int bh, int l, int r, int fl){
if(r < tl[bh] || l > tr[bh]) return 0;
if(tl[bh] >= l && tr[bh] <= r){
if(fl) return sum[bh];
else return tr[bh] - tl[bh] + 1 - sum[bh];
}
downdata(bh);
return query_sum(bh << 1, l, r, fl) + query_sum(bh << 1 | 1, l, r, fl);
}
void change(int t1, int t2, int d){
while(bl[t1] != bl[t2]){
if(dep[top[bl[t1]]] < dep[top[bl[t2]]]) swap(t1, t2);
modifiy(1, dfn[top[bl[t1]]], dfn[t1], d);
t1 = ft[top[t1]];
}
if(dfn[t1] > dfn[t2]) swap(t1, t2);
modifiy(1, dfn[t1], dfn[t2], d);
}
int ask_sum(int t1, int t2, int fl){
int ans = 0;
while(bl[t1] != bl[t2]){
if(dep[top[bl[t1]]] < dep[top[bl[t2]]]) swap(t1, t2);
ans += query_sum(1, dfn[top[bl[t1]]], dfn[t1], fl);
t1 = ft[top[bl[t1]]];
}
if(dfn[t1] > dfn[t2]) swap(t1, t2);
ans += query_sum(1, dfn[t1], dfn[t2], fl);
return ans;
}
int main(){
scanf("%d", &n);
for(int i = 2; i <= n; ++ i){
int x;
scanf("%d", &x);
++ x;
v[i].push_back(x);
v[x].push_back(i);
}
dfs1(1, 0);
cnt = 1;
top[1] = 1;
dfs2(1, 0, 1);
build(1, 1, n);
scanf("%d", &q);
while(q --){
string s;
int x;
cin >> s;
scanf("%d", &x);
++ x;
if(s == "install"){
int t = ask_sum(1, x, 0);
change(1, x, 1);
printf("%d\n", t);
}
else{
int t = query_sum(1, dfn[x], dfn[x] + siz[x] - 1, 1);
modifiy(1, dfn[x], dfn[x] + siz[x] - 1, 0);
printf("%d\n", t);
}
}
return 0;
}
最新发布