P2146 [NOI2015]軟體包管理器 ( 樹鏈剖分
阿新 • • 發佈:2018-12-11
題意:
樹剖水題:
操作1. 將一個點到根節點之間的序列, 統計 操作2.將一顆子樹的內部節點, 統計
//
// Created by Yishui on 2018/9/15.
//
#include <bits/stdc++.h>
using namespace std;
#define cpp_io() {ios::sync_with_stdio(false); cin.tie(NULL);}
#define rep(i,a,n) for (int i=a;i<n;i++)
#define repp(i,a,n) for (int i=a;i<=n;i++)
#define per(i,a,n) for (int i=n-1;i>=a;i--)
#define CLR(a,b) memset(a,(b),sizeof(a))
#define all(x) (x).begin(),(x).end()
#define SZ(x) ((int)(x).size())
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define ls o<<1
#define rs o<<1|1
typedef long long ll;
typedef vector<int> VI;
const int MAXN = (int)2e5+10;
const int INF = 0x3f3f3f3f;
const int mod = (int)1e9+7;
struct node{
int l,r;
int lazy,x;
int len;
}t[MAXN<<2];
int n,m;
int cnt;
int f[MAXN], d[MAXN], sz[MAXN], son[MAXN], rk[MAXN], top[MAXN], id[MAXN];
vector<int> E[MAXN];
int a[MAXN];
void push_down(int o){
if (t[o].lazy!=-1){
t[ls].x=t[ls].len*t[o].lazy;
t[rs].x=t[rs].len*t[o].lazy;
t[ls].lazy=t[o].lazy;
t[rs].lazy=t[o].lazy;
t[o].lazy=-1;
}
}
void build(int l,int r,int o) {
t[o].l=l,t[o].r=r;t[o].len=r-l+1;
t[o].lazy=-1; t[o].x=0;
if(l==r) return ;
int mid=(l+r)>>1;
build(l,mid,ls); build(mid+1,r,rs);
t[o].x=t[ls].x+t[rs].x;
}
inline void update(int l,int r, int o, int x) {
if(t[o].l>=l&&t[o].r<=r) {
t[o].x=t[o].len*x;
t[o].lazy=x;
return;
}
push_down(o);
int mid=(t[o].l+t[o].r)>>1;
if(r<=mid) update(l,r,ls,x);
else if(l>mid) update(l,r,rs,x);
else {
update(l,mid,ls,x); update(mid+1,r,rs,x);
}
t[o].x = t[ls].x+t[rs].x;
}
inline int query(int l,int r,int o){
if(t[o].l>=l&&t[o].r<=r) return t[o].x;
push_down(o);
int mid=(t[o].l+t[o].r)>>1;
if(r<=mid) return query(l,r,ls);
else if(l>mid) return query(l,r,rs);
else
return (query(l,mid,ls)+query(mid+1,r,rs));
}
// 樹上操作-----------------------------
void dfs1(int u, int fa, int dep){
f[u]=fa, d[u]=dep, sz[u]=1;
rep(i,0,SZ(E[u])){
int v=E[u][i];
if(v==fa) continue;
dfs1(v,u,dep+1);
sz[u]+=sz[v];
if(sz[v]>sz[son[u]]) son[u] = v;
}
}
void dfs2(int u,int t){
top[u]=t;
id[u]=++cnt;
rk[cnt]=u;
if(!son[u]) return;
dfs2(son[u],t);
rep(i,0,SZ(E[u])){
int v=E[u][i];
if(v!=son[u]&&v!=f[u]) dfs2(v,v);
}
}
void add_lca(int x,int y,int z) {
while(top[x]!=top[y]) {
if(d[top[x]]<d[top[y]]) swap(x,y);
update(id[top[x]],id[x],1,z);
x=f[top[x]];
}
if(d[x]>d[y]) swap(x,y);
update(id[x],id[y],1,z);
}
int main() {
cpp_io();
cin>>n;
repp(i,2,n) {
int u; cin>>u;++u;
E[u].pb(i); E[i].pb(u);
}
cin>>m;
cnt=0;
dfs1(1,0,1); dfs2(1,1);
build(1,n,1);
while(m--){
string s;
int u;int x1=t[1].x;
cin>>s>>u;++u;
if(s[0]=='i') {
add_lca(1,u,1);
cout<<abs(x1-t[1].x)<<endl;
}
else {
update(id[u],id[u]+sz[u]-1,1,0);
cout<<abs(x1-t[1].x)<<endl;
}
}
return 0;
}