题面传送门
N
O
I
NOI
NOI终于出了一道水题。
因为软件包之间有依赖,所以删除一个要把子树删完。安装一个要把路径上全部安装掉。直接树剖即可。
代码实现:
#include<cstdio>
#include<cstring>
using namespace std;
int n,m,k,x,y,son[100039],fa[100039],siz[100039],d[100039],id[100039],idea,top[100039],z,f[400039],sum[400039];
char _s;
struct yyy{int to,z;};
struct ljb{
int head,h[100039];
yyy f[200039];
inline void add(int x,int y){
f[++head]=(yyy){y,h[x]};
h[x]=head;
}
}s;
inline void push(int l,int r,int now){
int m=(l+r)>>1;
f[now<<1]=f[now<<1|1]=f[now];
sum[now<<1]=(f[now]+1)*(m-l+1)/2;
sum[now<<1|1]=(f[now]+1)*(r-m)/2;
f[now]=0;
}
inline void get(int x,int y,int z,int l,int r,int now){
if(x<=l&&r<=y) {f[now]=z,sum[now]=(z+1)*(r-l+1)/2;return;}
if(f[now]) push(l,r,now);
int m=(l+r)>>1;
if(x<=m) get(x,y,z,l,m,now<<1);
if(y>m) get(x,y,z,m+1,r,now<<1|1);
sum[now]=sum[now<<1]+sum[now<<1|1];
}
inline int find(int x,int y,int l,int r,int now){
if(x<=l&&r<=y) return sum[now];
if(f[now]) push(l,r,now);
int m=(l+r)>>1,fs=0;
if(x<=m) fs+=find(x,y,l,m,now<<1);
if(y>m) fs+=find(x,y,m+1,r,now<<1|1);
return fs;
}
inline void dfs1(int x,int last){
fa[x]=last;
siz[x]=1;
d[x]=d[last]+1;
int cur=s.h[x],pus=-1;
yyy tmp;
while(cur!=-1){
tmp=s.f[cur];
if(tmp.to!=last){
dfs1(tmp.to,x);
siz[x]+=siz[tmp.to];
if(siz[tmp.to]>pus) pus=siz[tmp.to],son[x]=tmp.to;
}
cur=tmp.z;
}
}
inline void dfs2(int x,int last){
top[x]=last;
id[x]=++idea;
if(!son[x]) return;
dfs2(son[x],last);
int cur=s.h[x];
yyy tmp;
while(cur!=-1){
tmp=s.f[cur];
if(tmp.to!=fa[x]&&tmp.to!=son[x]) dfs2(tmp.to,tmp.to);
cur=tmp.z;
}
}
inline void swap(int &x,int &y){x^=y,y^=x,x^=y;}
inline void get1(int x,int y){
while(top[x]!=top[y]){
if(d[top[x]]<d[top[y]]) swap(x,y);
get(id[top[x]],id[x],1,1,n,1);
x=fa[top[x]];
}
if(d[x]>d[y]) swap(x,y);
get(id[x],id[y],1,1,n,1);
//printf("%d\n",find(1,2,1,n,1));
}
inline int find1(int x,int y){
int ans=0;
while(top[x]!=top[y]){
if(d[top[x]]<d[top[y]]) swap(x,y);
ans+=find(id[top[x]],id[x],1,n,1);
//printf("%d ",ans);
x=fa[top[x]];
}
if(d[x]>d[y]) swap(x,y);
ans+=find(id[x],id[y],1,n,1);
return ans;
}
inline void get2(int x){get(id[x],id[x]+siz[x]-1,-1,1,n,1);}
inline int find2(int x){return find(id[x],id[x]+siz[x]-1,1,n,1);}
int main(){
register int i;
memset(s.h,-1,sizeof(s.h));
scanf("%d",&n);
for(i=2;i<=n;i++) scanf("%d",&x),x++,s.add(i,x),s.add(x,i);
dfs1(1,0);
dfs2(1,1);
scanf("%d",&m);
for(i=1;i<=m;i++){
_s=getchar();
while(_s<'a'||_s>'z')_s=getchar();
//printf("%d\n",find(1,2,1,n,1));
if(_s=='i'){
_s=getchar();_s=getchar();_s=getchar();_s=getchar();_s=getchar();_s=getchar();
scanf("%d",&x);
x++;
printf("%d\n",d[x]-find1(1,x));
get1(1,x);
}
else{
_s=getchar();_s=getchar();_s=getchar();_s=getchar();_s=getchar();_s=getchar();_s=getchar();_s=getchar();
scanf("%d",&x);
x++;
printf("%d\n",find2(x));
get2(x);
}
}
}