数据结构、算法总述:数据结构/算法 C/C++-CSDN博客
最小生成树(Minimum Spanning Tree,简称MST)是指在一个加权无向连通图中,包含图中全部顶点的、权值之和最小的生成树。生成树是原图的极小连通子图,包含图中所有的顶点,并且有保持图连通的最少的边。在这个定义中,“最小”是指树的所有边的权值之和最小。
prim算法
时间复杂度
: O(n^2+m), 用于稠密图
思路:
从图中的某一顶点开始,逐步增加新的边和顶点,直到形成最小生成树。
int n; // n表示点数
int g[N][N]; // 邻接矩阵,存储所有边
int dist[N]; // 存储其他点到当前最小生成树的距离
bool st[N]; // 存储每个点是否已经在生成树中
// 如果图不连通,则返回INF(值是0x3f3f3f3f), 否则返回最小生成树的树边权重之和
int prim()
{
memset(dist, 0x3f, sizeof dist);
int res = 0;
for (int i = 0; i < n; i ++ )
{
int t = -1;
for (int j = 1; j <= n; j ++ )
if (!st[j] && (t == -1 || dist[t] > dist[j]))
t = j;
if (i && dist[t] == INF) return INF;
if (i) res += dist[t];
st[t] = true;
for (int j = 1; j <= n; j ++ ) dist[j] = min(dist[j], g[t][j]);
}
return res;
}
题目:
858. Prim算法求最小生成树 - AcWing题库https://www.acwing.com/problem/content/860/
Kruskal算法
时间复杂度
: O(m*logm),用于稀疏图
思路:
按照边的权重顺序(从小到大)选择边,确保选择的边不会与已经选择的边形成环,直到形成最小生成树。
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;
}
题目:
859. Kruskal算法求最小生成树 - AcWing题库https://www.acwing.com/problem/content/861/