算法流程:
1.将所有边按照权重从小到大排序
2.枚举每条边ab,权重是c if a,b不连通,将这条边加入集合
代码模板:
int n, m; // n是点数,m是边数
int p[N]; // 并查集的父节点数组
struct Edge // 存储边
{
int a, b, w;
bool operator< (const Edge &W)const
{
return w < W.w;
}
}edges[M];
int find(int x) // 并查集核心操作
{
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
int kruskal()
{
sort(edges, edges + m);
for (int i = 1; i <= n; i ++ ) p[i] = i; // 初始化并查集
int res = 0, cnt = 0;
for (int i = 0; i < m; i ++ )
{
int a = edges[i].a, b = edges[i].b, w = edges[i].w;
a = find(a), b = find(b);
if (a != b) // 如果两个连通块不连通,则将这两个连通块合并
{
p[a] = b;
res += w;
cnt ++ ;
}
}
if (cnt < n - 1) return INF;
return res;
作者:yxc
链接:https://www.acwing.com/blog/content/405/
来源:AcWing
例题:
给定一个 n 个点 m条边的无向图,图中可能存在重边和自环,边权可能为负数。求最小生成树的树边权重之和,如果最小生成树不存在则输出 impossible
。给定一张边带权的无向图 G=(V,E),其中 V 表示图中点的集合,E 表示图中边的集合,n=|V|,m=|E|。由 V中的全部 n 个顶点和 E 中 n−1 条边构成的无向连通子图被称为 G 的一棵生成树,其中边的权值之和最小的生成树被称为无向图 G的最小生成树。
输入格式
第一行包含两个整数 n和 m。
接下来 m行,每行包含三个整数 u,v,w,表示点 u 和点 v 之间存在一条权值为 w的边。
输出格式
共一行,若存在最小生成树,则输出一个整数,表示最小生成树的树边权重之和,如果最小生成树不存在则输出 impossible
。
数据范围
1≤n≤105,1≤m≤2∗105,
图中涉及边的边权的绝对值均不超过 1000。
输入样例:
4 5
1 2 1
1 3 2
1 4 3
2 3 2
3 4 4
输出样例:
6
代码:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 100010,M = 200010, INF = 0x3f3f3f3f;
int n,m;
int p[N];
struct Edge{
int a,b,w;
bool operator< (const Edge &W)const{
return w < W.w;
}
}edges[M];
int find(int x){
if(x != p[x])p[x] = find(p[x]);
return p[x];
}
int Kruskal(){
sort(edges,edges+m);
for(int i=1;i<=n;i++)p[i]=i;
int res=0,cnt=0;
for(int i=0;i<m;i++){
int a = edges[i].a,b = edges[i].b,c = edges[i].w;
a = find(a),b = find(b);
if(a != b){
p[a]=b;
res += c;
cnt++;
}
}
if(cnt < n-1)return INF;
return res;
}
int main()
{
cin>>n>>m;
int a,b,w;
for(int i=0;i<m;i++){
cin>>a>>b>>w;
edges[i] = {a,b,w};
}
if(Kruskal()!=INF)cout<<Kruskal();
else cout<<"impossible";
return 0;
}