题解:
Prim算法。因为该图为完全图,用邻接矩阵存储。注意所开数组的大小及判断条件。
代码如下:
#include#define MaxVex 110int MGraph[MaxVex][MaxVex];typedef struct Closedge{ int adjvex; int lowcost;}closedge[MaxVex];int minimum(closedge &ce, int n){ int i = 1, k, min; while (!ce[i].lowcost)//辅助数组中第1个非零数 i++; min = ce[i].lowcost; k = i; for (; i<=n; i++) { //找出辅助数组中的最小值(除零外) if (ce[i].lowcost) { if (ce[i].lowcost < min) { k = i; min = ce[k].lowcost; } } } return k;//返回辅助数组的非零最小值的下标}int main(){ //Prim算法: int k, i, j, n, m, sum; closedge ce; while (scanf("%d", &n) && n) { for (k=1; k<=n*(n-1)/2; k++) { //邻接矩阵初始化 scanf("%d%d%d", &i, &j, &m); MGraph[i][j] = MGraph[j][i] = m; } k = 1;//从1开始构造最小生成树 for (j=1; j<=n; j++) { //辅助数组初始化 if (k != j) { ce[j].adjvex = k; ce[j].lowcost = MGraph[k][j]; } } sum = ce[k].lowcost = 0; //初始:U = {u}, sum; for (i=1; i