c++普利姆最小生成树算法代码
时间: 2024-12-16 10:13:25 浏览: 16
普里姆(Prim's Algorithm)是一种用于寻找无向图中最小生成树(Minimum Spanning Tree,MST)的经典算法。在C++中实现普利姆算法,一般会采用邻接矩阵或邻接表数据结构。以下是基于邻接矩阵的一个简化版本:
```cpp
#include <iostream>
#include <vector>
using namespace std;
struct Edge {
int from, to, weight;
};
bool compareWeight(Edge a, Edge b) {
return a.weight < b.weight;
}
void prim(vector<Edge>& edges, vector<bool>& visited, int start, vector<int>& mst) {
int n = edges.size();
visited.resize(n, false);
mst.clear();
visited[start] = true;
mst.push_back(start);
for (int i = 0; i < n; ++i) {
Edge min_edge = {INT_MAX, -1, INT_MAX};
for (int j = 0; j < n; ++j) {
if (!visited[j] && edges[j].weight < min_edge.weight) {
min_edge = edges[j];
}
}
visited[min_edge.to] = true;
mst.push_back(min_edge.to);
// 更新已添加到MST的边
for (Edge& edge : edges) {
if (!visited[edge.from] && !visited[edge.to] && edge.weight < min_edge.weight) {
min_edge = edge;
}
}
}
}
int main() {
vector<Edge> edges = {{0, 1, 4}, {0, 7, 8}, {1, 2, 8}, {1, 6, 7}, {2, 3, 9}, {2, 5, 5},
{3, 4, 11}, {3, 6, 1}, {4, 5, 7}, {5, 6, 4}, {6, 7, 2}};
vector<bool> visited(edges.size());
vector<int> mst;
prim(edges, visited, 0, mst);
cout << "Minimum spanning tree using Prim's algorithm:" << endl;
for (int node : mst) {
cout << node << " ";
}
cout << endl;
return 0;
}
```
这个代码首先定义了一个Edge结构体表示每条边,然后通过prim函数找到从起点开始的最小生成树。注意,这只是一个基本示例,实际应用中可能需要处理更复杂的数据结构和边界情况。
阅读全文