跳到正文

算法·理论

树上启发式合并学习笔记

YangShaoQi_1e8约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年5月20日
收录
2026年10月27日
更新
2026年11月21日
篇幅
约 4 分钟

版本

  1. v1当前

树上启发式合并(dsu on tree)学习笔记

上上周学了树上启发式合并,写篇笔记吧

能干的事

树上的一些颜色问题,不支持在线,主要是子树颜色统计之类的

实现思路

长得跟暴搜挺像的,主要是在遍历的过程中弄一个全局的 cntcnt 数组,计算有关节点对当前节点的影响,大致分为三步

1.遍历轻儿子,计算答案后不保留对 cntcnt 的影响
2.遍历重儿子,计算答案后保留对 cntcnt 的影响
3.如果不用保留答案,把当前节点的影响清除掉

在实现过程中对 cntcnt 的修改我们采用 dfn 序 来实现,我们可以预处理出每个节点的子树 dfndfn 序的区间,实现快速修改

大板子题

给一棵树,每个节点有颜色,求每个节点的子树中颜色数量
代码如下

C++
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
int n;//           节点数
int u,v;//         输入用的
int c[N];//        节点颜色
int L[N],R[N];//   子树dfn序左右区间
int id[N],tot;//   由dfn映射到原节点用的东西
int len[N];//      子树大小
int son[N];//      重儿子
int cnt[N];//      统计当前每种颜色出现数量
int col;//         当前颜色种类数
int ans[N];//      答案
vector<int>g[N];// 邻接表
void dfs(int x,int fat){   //  预处理
    len[x]=1;
    L[x]=++tot;
    id[tot]=x;
    for(int i=0;i<g[x].size();i++){
        int to=g[x][i];
        if(to==fat) continue;
        dfs(to,x);
        len[x]+=len[to]; // 求子树大小
        if(len[son[x]]<len[to]) son[x]=to;  // 求重儿子
    }
    R[x]=tot;
}
void update(int x,int p){ //  修改单点
    if(cnt[c[x]]==0) col++; //  如果原来没有,颜色种类增加
    cnt[c[x]]+=p;
    if(cnt[c[x]]==0) col--; //  如果改完没了,颜色种类减少
}
void add(int x,int p){//  修改子树
    for(int i=L[x];i<=R[x];i++){  
        update(id[i],p);
    }
}
void dsu(int x,int fat,bool ok){
    for(int i=0;i<g[x].size();i++){ //  走轻儿子
        int to=g[x][i];
        if(to==fat) continue;
        if(to==son[x]) continue;
        dsu(to,x,0);  //  不保留答案
    }
    if(son[x]) dsu(son[x],x,1);  //  走重儿子,保留答案
    //  注意一定要判有无重儿子
    for(int i=0;i<g[x].size();i++){
        int to=g[x][i];
        if(to==fat) continue;
        if(to==son[x]) continue;
        add(to,1);  //  统计每个子节点答案
    }
    update(x,1);  //  把自己加上
    ans[x]=col;
    if(!ok) add(x,-1); // 如果不用保留,全删掉 
}
int main(){
    cin>>n;
    for(int i=1;i<=n;i++) cin>>c[i];
    for(int i=1;i<n;i++){
        cin>>u>>v;
        g[u].push_back(v);
        g[v].push_back(u);
    }
    dfs(1,-1);
    dsu(1,-1,0);
    for(int i=1;i<=n;i++) cout<<ans[i]<<' ';
    return 0;
}

时间复杂度

每个节点只会被轻边遍历到,轻边数是 log2(n)log_2(n) 的,因此时间复杂度 nlog2(n)nlog_2(n)

原文