P2146 [NOI2015] 软件包管理器 题解
单
定义
注意到安装结点构成一个包含根的连通块。
考虑用 set 按照 DFS 序维护连通块的叶子。
安装点
卸载点
LCA 算法可以任意选取,时间复杂度根据 LCA 算法的预处理复杂度为
代码使用了 DFS 序 RMQ 求 LCA,复杂度为前者。
#include <bits/stdc++.h>
using namespace std;
constexpr int N(1e5),LG{16};
vector<int> e[N+5];
int L[N+5],R[N+5],fz[N+5],dep[N+5],st[LG+5][N+5],fa[N+5];
int Max(int x,int y) {
return dep[fz[x]]<dep[fz[y]]?x:y;
}
void init(int u) {
static int lda{0};
L[u]=++lda;
fz[lda]=u;
for (auto v:e[u])
dep[v]=dep[u]+1,init(v);
R[u]=lda;
}
int n;
int LCA(int u,int v) {
if (u==v) return u;
if (u==0||u==n+1||v==0||v==n+1) return 0;
u=L[u];v=L[v];
if (u>v) swap(u,v);
int z{__lg(v-u)};
return fa[fz[Max(st[z][u+1],st[z][v-(1<<z)+1])]];
}
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
cin>>n;
for (int i{2};i<=n;++i) {
cin>>fa[i];
++fa[i];
e[fa[i]].push_back(i);
}
dep[1]=1;
init(1);
iota(*st+1,*st+1+n,1);
for (int i{1};i<=LG;++i)
for (int j{1};j+(1<<i)-1<=n;++j)
st[i][j]=Max(st[i-1][j],st[i-1][j+(1<<i-1)]);
set<int> s{0,n+1};
int q;cin>>q;
L[n+1]=fz[n+1]=n+1;
while (q--) {
char op[100];cin>>op;
int x;cin>>x;
++x;
if (op[0]=='i') {
int P{fz[*prev(s.lower_bound(L[x]))]},Q{fz[*s.lower_bound(L[x])]};
if (L[Q]<=R[x]) {
cout<<"0\n";
continue;
}
if (R[P]>=L[x]) s.erase(L[P]);
s.insert(L[x]);
cout<<dep[x]-max(dep[LCA(P,x)],dep[LCA(x,Q)])<<"\n";
} else {
int lst{fa[x]},ans{0};
if (*s.lower_bound(L[x])>R[x]) {
cout<<"0\n";
continue;
}
for (auto it{s.lower_bound(L[x])};*it<=R[x];) {
ans+=dep[fz[*it]]-dep[LCA(lst,fz[*it])];
lst=fz[*it];
it=s.erase(it);
}
if (*s.lower_bound(L[x])>R[fa[x]]&&*prev(s.lower_bound(L[x]))<L[fa[x]])
s.insert(L[fa[x]]);
cout<<ans<<"\n";
}
}
return 0;
}