题面
https://www.luogu.org/problem/P2146
题解
#include<cstdio> #include<iostream> #include<vector> #define N 100050 #define ri register int using namespace std; int n,m,clo=0,ans; vector<int> son[N]; int siz[N],top[N],dfin[N],dfou[N],dep[N],fa[N]; void dfs1(int x,int d){ siz[x]=1; dep[x]=d; for (ri i=son[x].size()-1;i>=0;i--) { dfs1(son[x][i],d+1); siz[x]+=siz[son[x][i]]; } } void dfs2(int x,int tp) { int fs,ms=0; dfin[x]=++clo; top[x]=tp; if (son[x].size()) { for (ri i=son[x].size()-1;i>=0;i--) if (siz[son[x][i]]>ms) ms=siz[son[x][i]],fs=son[x][i]; dfs2(fs,tp); for (ri i=son[x].size()-1;i>=0;i--) if (son[x][i]!=fs) dfs2(son[x][i],son[x][i]); } dfou[x]=clo; } int lb[4*N],rb[4*N],val[4*N],add[4*N]; void maketree(int x,int l,int r) { lb[x]=l; rb[x]=r; val[x]=0; if (l==r) return; int mid=(l+r)/2; maketree(2*x,l,mid); maketree(2*x+1,mid+1,r); } void pushdown(int x){ if (add[x]==0) return; if (add[x]==1) { val[2*x]=rb[2*x]-lb[2*x]+1; add[2*x]=1; val[2*x+1]=rb[2*x+1]-lb[2*x+1]+1; add[2*x+1]=1; } else { val[2*x]=0; add[2*x]=2; val[2*x+1]=0; add[2*x+1]=2; } add[x]=0; } void count(int x,int l,int r) { // count0 0->1 if (l<=lb[x] && rb[x]<=r) { ans+=(rb[x]-lb[x]+1-val[x]); val[x]=rb[x]-lb[x]+1; add[x]=1; return; } if (l>rb[x] || r<lb[x]) return; pushdown(x); count(2*x,l,r); count(2*x+1,l,r); val[x]=val[2*x]+val[2*x+1]; } void count2(int x,int l,int r) { //count1 1->0 if (l<=lb[x] && rb[x]<=r) { ans+=val[x]; val[x]=0; add[x]=2; return; } if (l>rb[x] || r<lb[x]) return; pushdown(x); count2(2*x,l,r); count2(2*x+1,l,r); val[x]=val[2*x]+val[2*x+1]; } void ins(int x) { while (x) { count(1,dfin[x]-(dep[x]-dep[top[x]]),dfin[x]); x=fa[top[x]]; } } void del(int x) { count2(1,dfin[x],dfou[x]); } int main(){ scanf("%d",&n); int x; for (ri i=2;i<=n;i++) { scanf("%d",&x); x++; fa[i]=x; son[x].push_back(i); } dfs1(1,1); dfs2(1,0); maketree(1,1,n); int q; scanf("%d",&q); char s[10]; for (ri i=1;i<=q;i++) { scanf("%s %d",s,&x); x++; ans=0; if (s[0]=='i') ins(x); else del(x); printf("%d ",ans); } }