普里姆算法求最小生成树(MST-Prim algorithm)

最小生成树:带权图的生成树上的各边权 值之和称为这棵树的代价。最小代价生成 树是各边权值的总和最小的生成树。

普里姆算法(Prim)步骤:
1、选取源点作为最小生成树的结点,并初始化当前与生成树相连的最好情况,即权值最小的边

2、选取权值最小的边加入生成树,并更新各顶点的最好情况。

3、重复步骤2,直到所有顶点都加入生成树当中。

代码如下:
 
#include<stdio.h> #include<string.h> #include<iostream> #define MAX 100 #define INF 10000000 typedef struct { int adjvex; //存放的这条权值最小的边的另一个顶点 int lowcost;           //存放的这条权值最小的边的权值 }Path; typedef struct { int arc[MAX][MAX]; int arcnum, vexnum; }AGraph; AGraph T; int minclosedge(Path closedge[]) { int min, j, k; min = INF; k = -1; for (j = 0; j < T.vexnum; j++) { if (closedge[j].lowcost != 0 && closedge[j].lowcost < min) { min = closedge[j].lowcost; k = j; } } return k; } void prim(AGraph T, int u) //起点为u { int i, j, k; Path closedge[MAX]; for (j = 0; j < T.vexnum; j++) { closedge[j].adjvex = u; closedge[j].lowcost = T.arc[u][j]; } closedge[u].lowcost = 0; // closedge[w].lowcost==0表示w已经加入生成树 for (i = 1; i < T.vexnum; i++) { k = minclosedge(closedge); printf("<%d,%d> ", closedge[k].adjvex, k); closedge[k].lowcost = 0; for (j = 0; j < T.vexnum; j++) { if (T.arc[k][j] < closedge[j].lowcost) { closedge[j].lowcost = T.arc[k][j]; closedge[j].adjvex = k; } } } } int main() { int i, j; printf("请输入图的顶点数:\n"); scanf_s("%d", &T.vexnum); printf("请%d阶输入邻接矩阵的值:\n", T.vexnum); for(i = 0; i < T.vexnum; i++) for (j = 0; j < T.vexnum; j++) scanf_s("%d", &T.arc[i][j]); prim(T, 0); //起点为0 system("pause"); }

编译环境: Visual Studio
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值