P2146 [NOI2015] 软件包管理器 题解

· · 题解

单 \log 做法。

定义 dep_u 为点 u 的深度。

注意到安装结点构成一个包含根的连通块。

考虑用 set 按照 DFS 序维护连通块的叶子。

安装点 x 的时候,先检查 set 中有没有它子树内的点,如果有则无需安装。否则,找到它最深的安装的祖先,这个可以在 set 中找到 DFS 序上前后最近的点并求取 LCA 得到,然后我们就可以得知本次答案为 dep_x-dep_a,a 为找到的祖先。随后将该点加入 set,并检查刚才的祖先在不在其中,如果在则删除。

卸载点 x 也是类似的。将它子树内的叶子全部从 set 中删除,如果不存在则无需卸载。否则,计算刚才删除的连通块的大小。具体地。设删除的点按照 DFS 序从小到大为 a_1,a_2,\dots,a_m,且令 a_0=x,则答案为 \sum_{i=1}^m dep_{a_i}-dep_{\text{LCA}(a_i,a_{i-1})},可以画图理解。

LCA 算法可以任意选取,时间复杂度根据 LCA 算法的预处理复杂度为 O((n+q)\log n) 或 O(n+q\log n)。

代码使用了 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;
}