最小生成树prim算法c++
时间: 2023-11-03 13:49:38 浏览: 132
Sure, I'd be happy to discuss the Prim's minimum spanning tree algorithm in C with you. Prim's algorithm is a greedy algorithm that finds a minimum spanning tree for a weighted undirected graph. The algorithm starts by creating a tree with a single vertex, then iteratively adds the cheapest edge not yet in the tree that connects to an unvisited vertex, until all vertices are visited. Let me know if you have any specific questions about the implementation in C!
相关问题
最小生成树prim算法C++
以下是C++实现Prim算法求解最小生成树的代码示例:
```c++
#include <iostream>
#include <cstring>
using namespace std;
const int N = 510;
int g[N][N]; // 存储图的邻接矩阵
int dist[N]; // 存储当前生成树到每个点的最短距离
bool st[N]; // 存储每个点是否已经加入生成树
int prim(int n)
{
memset(dist, 0x3f, sizeof dist); // 初始化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] == 0x3f3f3f3f) return -1; // 如果当前生成树不连通,则返回-1
if (i) res += dist[t]; // 将当前点加入生成树,并将边的权值加入res
st[t] = true; // 标记当前点已经加入生成树
for (int j = 1; j <= n; j ++ )
dist[j] = min(dist[j], g[t][j]); // 更新当前生成树到每个点的最短距离
}
return res;
}
int main()
{
int n, m;
cin >> n >> m;
memset(g, 0x3f, sizeof g); // 初始化邻接矩阵为无穷大
while (m -- )
{
int a, b, c;
cin >> a >> b >> c;
g[a][b] = g[b][a] = min(g[a][b], c); // 存储边的权值
}
int t = prim(n); // 求解最小生成树的权值和
if (t == -1) puts("impossible"); // 如果当前图不连通,则输出impossible
else cout << t << endl; // 输出最小生成树的权值和
return 0;
}
```
最小生成树Prim算法C++
Prim算法是一种用于求解加权无向连通图的最小生成树的算法。它的基本思想是从一个任意结点开始,每次选择一个与当前生成树相邻的权值最小的结点加入生成树中,直到所有结点都被加入为止。下面是Prim算法的C++代码实现,其中邻接表存储图结构:
```
void Prim(GraphList G,int v) {
int flag = 0; //定位当前选择的结点的在定点表中的下标位置
int sum = 0; //最小生成树的权值之和
int min = 9999; //游标,最小权值,后面对比边权值用
int j = 1;
visited[v] = 1; //初始节点标记已访问
Node[0] = v; //将初始结点放入以访问结点数组中
EdgeNode* p = new EdgeNode;
while (j < G.vexnum) {
int i = 0;
min = 9999;
while (Node[i] != -1) {
for (p = G.Vexlist[Node[i]].first; p; p = p->next) {
if (min > p->weight && visited[p->adjvex] == 0) //在所有已经访问的结点中,找出与为访问结点相邻的边的权值最小的那条边和相邻的结点
{
min = p->weight;
flag = p->adjvex;
}
}
i++;
}
sum += min;
Node[j] = flag;
visited[flag] = 1;
j++;
}
cout << "最小生成树权值之和: " << sum << endl;
}
```
阅读全文