跳到正文

算法·理论

Kruskal 重构树学习笔记 || 未完工

Segment_Fenwick_Tree约 6 分钟
原文
文章信息与版本

文章信息

发布
2026年9月12日
收录
2026年11月27日
更新
2026年11月27日
篇幅
约 6 分钟

版本

  1. v1当前

Kruskal 重构树,多用于求解生成树中最小边权最大,最大边权最小等问题,在跑 Kruskal 加边的同时建树,以加速需要处理的问题。

P1967 [NOIP 2013 提高组] 货车运输

板子题。

定义一条路径的权值为路径中边权最小的边的边权。

题目需要我们多次查询从 uu 到 vv 的所有路径中权值最大的路径的权值。

思考一下这个权值是怎么来的。

对原图的边权降序排序,跑 Kruskal,当 uu 和 vv 第一次联通的时候,此时加入的边的边权就是答案。因为这里加入的边都是尽可能大的。

考虑 Kruskal 的本质。

在刚学 OI 的时候,我们知道 Kruskal 每次加边,相当于将两个集合合并,所以用并查集。

那我们能不能把这两个集合看作两棵树,而合并相当于新建一个点权为加入边的边权的父节点,而儿子是这两棵的根节点呢?

这个方法也太牛了,因为这里我们是降序排序边权的,每次加入的边的边权也一定是单调不增的,所以对于两个新建节点 aa 和 bb,当 aa 是 bb 的父亲节点时,aa 的点权一定是小于 bb 的点权的。

结合刚才的权值计算方法,可以发现,当 uu 和 vv 第一次联通时,新建的那个点一定是 uu 和 vv 的最近公共祖先!

所以在每次查询时直接求最近公共祖先即可。

C++
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pii pair<ll,ll>
#define dgd priority_queue<int>
#define xgd priority_queue<int,vector<int>,greater<int> >
#define fi first
#define se second
#define pbk push_back
#define all(_c) _c.begin(),_c.end()
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)
#define nl cout << "\n"
const int INF=1e9;
const ll Inf=4e18;
const int abc=26;
const double pi=3.1415926;
int read(){
    int x=0,f=1;char c=getchar();
    while(c<'0'||c>'9'){if(c=='-') f=-1;c=getchar();}
    while(c>='0'&&c<='9'){x=x*10+c-48;c=getchar();}
    return x*f;
}
int n,m,q,x,y,top,cnt,rt,f[20010],c[20010],anc[20010][20],dep[20010],vis[20010];
struct edge{
	int u,v,w;
}s[50010];
bool cmp(edge a,edge b){
    return a.w>b.w;
}
vector<int> g[20010];
int Find(int x){
    if(f[x]==x) return x;
    return f[x]=Find(f[x]);
}
void kruskal(){
    rep(i,1,n) f[i]=i;
    top=n;
	rep(i,1,m){
        if(cnt==n-1) break;
        s[i].u=Find(s[i].u);s[i].v=Find(s[i].v);
        if(s[i].u!=s[i].v){
            top++;
            c[top]=s[i].w;f[top]=top;
            f[s[i].u]=f[s[i].v]=top;//关键一步:新建节点并向u,v连边
            g[top].pbk(s[i].u);g[top].pbk(s[i].v);
        }
    }
    return;
}
void dfs(int u,int f){
    vis[u]=1;anc[u][0]=f;
    dep[u]=dep[f]+1;
    rep(i,1,19) anc[u][i]=anc[anc[u][i-1]][i-1];
    for(auto v:g[u]){
        if(v==f || vis[v]) continue;
        dfs(v,u);
    }
    return;
}
int Query(int x,int y){//LCA板子
    if(dep[x]<dep[y]) swap(x,y);
    per(i,19,0) if(dep[anc[x][i]]>=dep[y]) x=anc[x][i];
    if(x==y) return c[x];
    per(i,19,0) if(anc[x][i]!=anc[y][i]) x=anc[x][i],y=anc[y][i];
    return c[anc[x][0]];//最后得出的LCA的点权就是最大值
}
void solve(){
	cin >> n >> m;
	rep(i,1,m){
		cin >> s[i].u >> s[i].v >> s[i].w;
	}
	sort(s+1,s+m+1,cmp);
	kruskal();
    rep(i,1,top) if(!vis[i]) dfs(Find(i),0);//因为可能有多棵树,所以要对于每个根节点都跑一遍!!!
    cin >> q;
    while(q--){
        cin >> x >> y;
        if(Find(x)!=Find(y)) cout << "-1\n";
        else cout << Query(x,y) << "\n";
    }
    nl;
    return;
}
int main(){
    ios::sync_with_stdio(false);
    cout.tie(0),cin.tie(0);
    int t=1;
    //cin >> t;
    while(t--) solve();
    return 0;
}


原文