树链剖分(轻重链剖分)一般写法的爆栈问题

· · 算法·理论

1.一般写法

这是对于一般树链剖分写法的极端测试。测试中我构造了一条长度仅为 150000 的链,就使得这份来自 OI-wiki 的树链剖分标准代码在本地爆栈了。 :::info[测试代码]

#include<bits/stdc++.h>
using namespace std;
constexpr int N=150000;
vector<int> G[N+5];
int fa[N+5],dep[N+5],siz[N+5],son[N+5];
int top[N+5],dfn[N+5],rnk[N+5],idx;
//Functions dfs1, dfs2 and lca are from oi-wiki.org/graph/hld/
void dfs1(int u, int f) {
    fa[u] = f, dep[u] = dep[f] + 1, siz[u] = 1;
    for (auto v : G[u]) {
        if (v == f) continue;
        dfs1(v, u);
        siz[u] += siz[v];
        if (siz[v] > siz[son[u]]) son[u] = v;
    }
}
void dfs2(int u, int ftop) {
    top[u] = ftop, dfn[u] = ++idx, rnk[idx] = u;
    if (son[u]) dfs2(son[u], ftop);
    for (auto v : G[u])
        if (v != son[u] && v != fa[u]) dfs2(v, v);
}
int lca(int u, int v) {
    while (top[u] != top[v]) {
        if (dep[top[u]] > dep[top[v]])
            u = fa[top[u]];
        else
            v = fa[top[v]];
    }
    return dep[u] > dep[v] ? v : u;
}
int p[N+5];
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    for(int i=1;i<=N;i++) p[i]=i;
    shuffle(p+1,p+N+1,mt19937(114514));
#define pb push_back
    for(int i=2;i<=N;i++) G[p[i]].pb(p[i-1]),G[p[i-1]].pb(p[i]);
    dfs1(p[1],0),dfs2(p[1],p[1]);
    cout<<lca(1919,810)<<'\n';
    return 0;
}

:::

2.为什么你写了这么长时间的树链剖分没被卡?

以下是一些 OJ 的栈空间大小。 :::info[统计(by AI)]

OJ 平台 栈空间大小 类型 说明
AtCoder = 内存限制 动态 默认为 1024MB,基本不会爆栈
NOI / NOIP (CCF)~(好像不算OJ 罒ω罒)~ = 内存限制 动态 有明确规定
洛谷 Luogu = 内存限制 动态 遵循 CCF 惯例
LOJ (LibreOJ) = 内存限制 动态 OI 导向平台,栈空间等于题目内存限制
Codeforces 256MB 固定 编译命令含 -Wl,--stack=268435456,固定 256MB
牛客 NowCoder 256MB 固定 ACM 风格,栈空间较宽裕
AcWing 8MB 固定 Linux 默认值,不等于内存限制
SPOJ 8MB 固定 Linux 默认值
POJ 8MB 固定 Linux 默认值,老平台
HDU ~1MB 固定 Windows 服务器,极易爆栈

::: 众所周知,递归树链剖分需要两次 DFS,估计每层栈帧约 100–200 字节。也就是说,在一个只有 1e5 个点的链上,单次 DFS 也需要 10MB 栈空间。

也就是说,如果需要在 HDU,AcWing,SPOJ,POJ 等栈空间不充裕的 OJ 上提交,那么就极易爆栈。

而我的本地使用的是 MinGW-w64 GCC 16.1.0 编译器,栈空间只有 1MB ,测小样例还没事,但凡自己造一组大数据,就必炸无疑。

3.怎么办?

把 DFS 都改成 BFS 就好了。~虽然涉及从下往上的更新可能不好做,但是安全最重要。~

贴出我的 HLD 模版,可能包含自己的使用习惯,如果需要,改掉即可。 :::info[模版HLD] 基于广为流传的HLD模版自己改的,有注释。

struct HLD{
    int n,cur;
    vector<int> siz,top,dep,fa,in,out,seq,order;
    //Order : The dp-order of the tree from leaves to root.
    //Root to Leaves : reverse(order).
    vector<vector<int>> adj;
    HLD(){}
    HLD(int n){init(n);}
    void init(int n_){
        n=n_+1;
        siz.resize(n),top.resize(n),dep.resize(n);
        fa.resize(n),in.resize(n),out.resize(n);
        seq.resize(n),cur=0,adj.assign(n,{}),n=n_;
    }
    void addEdge(int u,int v){adj[u].pb(v),adj[v].pb(u);}
    void bfs1(int root){
        vector<int> stk={root};
        order.clear();
        while(!stk.empty()){
            int u=stk.back();order.pb(u);
            stk.pop_back();
            if(fa[u]!=-1) adj[u].erase(find(adj[u].begin(),adj[u].end(),fa[u]));
            for(auto v:adj[u]){fa[v]=u,dep[v]=dep[u]+1,stk.pb(v);}
        }
        reverse(order.begin(),order.end());
        for(auto u:order){
            siz[u]=1;
            for(auto&v:adj[u]){
                siz[u]+=siz[v];
                if(siz[v]>siz[adj[u][0]]) swap(v,adj[u][0]);
            }
        }
    }
    void bfs2(int root){
        struct Frame{int u,stage;};
        vector<Frame> stk;
        stk.reserve(n);
        stk.pb({root,0});
        while(!stk.empty()){
            auto&[u,stage]=stk.back();
            if(stage==0){
                seq[in[u]=++cur]=u,stage=1;
                per(i,SZ(adj[u])-1,0,1){
                    int v=adj[u][i];
                    top[v]=(v==adj[u][0]?top[u]:v),stk.pb({v,0});
                }
            }else out[u]=cur+1,stk.pop_back();
        }
    }
    void work(int root=1){
        top[root]=root,dep[root]=0,fa[root]=-1;
        bfs1(root),bfs2(root);
    }
    int lca(int u,int v){
        while(top[u]!=top[v]){
            if(dep[top[u]]>dep[top[v]]) u=fa[top[u]];
            else v=fa[top[v]];
        }
        return dep[u]<dep[v]?u:v;
    }
    int dist(int u,int v){return dep[u]+dep[v]-2*dep[lca(u,v)];}
    int jump(int u,int k){
        //The k-th Ancester of vertex u.
        if(dep[u]<k) return -1;
        int d=dep[u]-k;
        while(dep[top[u]]>d) u=fa[top[u]];
        return seq[in[u]-dep[u]+d];
    }
    bool isAncester(int u,int v){return in[u]<=in[v] && in[v]<out[u];}
    int rootedFa(int u,int v){
        //The father of vertex v when vertex u is the root.
        swap(u,v);
        if(u==v) return u;
        if(!isAncester(u,v)) return fa[u];
        auto it=upper_bound(adj[u].begin(),adj[u].end(),v,[&](int x,int y){
            return in[x]<in[y];
        })-1;
        return *it;
    }
    int rootedSize(int u,int v){
        //The size of vertex v when vertex u is the root.
        if(u==v) return n;
        if(!isAncester(v,u)) return siz[v];
        return n-siz[rootedFa(u,v)];
    }
    int rootedLca(int a,int b,int c){
        //The lca of a and b when c is the root.
        return lca(a,b)^lca(b,c)^lca(c,a);
    }
};

:::