Prim算法,适用于密集的结构
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
void primMST(const vector<vector<int>> &graph) {
int vertices = graph.size();
vector<int> key(vertices, INT_MAX); // 每个顶点的最小权值
vector<bool> inMST(vertices, false); // 是否包含在MST中
vector<int> parent(vertices, -1); // 最小生成树的父节点
key[0] = 0; // 从第一个顶点开始
for (int count = 0; count < vertices - 1; ++count) {
int u = -1, minKey = INT_MAX;
// 找到未包含在MST中且key值最小的顶点
for (int v = 0; v < vertices; ++v) {
if (!inMST[v] && key[v] < minKey) {
minKey = key[v];
u = v;
}
}
inMST[u] = true; // 将该顶点加入MST
// 更新与u相邻的顶点的key值
for (int v = 0; v < vertices; ++v) {
if (graph[u][v] && !inMST[v] && graph[u][v] < key[v]) {
key[v] = graph[u][v];
parent[v] = u;
}
}
}
// 输出MST
cout << "Edge \tWeight" << endl;
for (int i = 1; i < vertices; ++i) {
cout << parent[i] << " - " << i << "\t" << graph[i][parent[i]] << endl;
}
}
int main() {
vector<vector<int>> graph = {
{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0}
};
cout << "Prim's Minimum Spanning Tree:" << endl;
primMST(graph);
return 0;
}