源代码如下:
#include<iostream> using namespace std; #define MAX_VERTEX_NUM 20 #define infinity 9 typedef int QElemType; typedef int EdgeData; typedef char VertexData; typedef struct { VertexData verlist[MAX_VERTEX_NUM]; //顶点表 EdgeData edge[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; //邻接矩阵--可试为边之间的关系 int vexnum,edgenum; //顶点数和边数 }MTGraph; void printMTGragh(MTGraph *G){ int i,j; for (i = 1 ; i <= G->vexnum ; i++){ for (j = 1 ; j <= G->vexnum ; j++) cout<<G->edge[i][j]<<" "; cout<<endl; } // Prim(G,G->edge); } void Prim(MTGraph *G){ //集合V-U的顶点尚未加入最小生成树中,集合U则已加入 int lowcost[MAX_VERTEX_NUM+1]; //用来保存集合V-U中各顶点与集合U中顶点最短边的权值, // lowcost[v] = infinity 表示顶点V已加入了最小生成树中 int closest[MAX_VERTEX_NUM+1]; //用来保存依附于该边的在集合U的顶点 // 该边:集合V-U中各顶点与集合U中顶点最短边 int i,j,k,h,min; // printMTGragh(G); for(i = 2;i<=G->vexnum;i++){ lowcost[i] = G->edge[1][i]; closest[i] = 1; //将定点1加入集合U中 } for(i = 2;i<=G->vexnum;i++){ min = 9 ; k = i; for(j=2;j<=G->vexnum;j++) if(lowcost[j] < min && lowcost[j]!=0){ min = lowcost[j]; //在 lowcost中取最小边 k = j; } cout<<"将第"<<i<<"个元素放入集合U中时,Lowcost原序列:"; for(h = 2;h<=G->vexnum;h++) cout<<lowcost[h]<<" "; cout<<endl; cout<<"("<<k<<","<<closest[k]<<")"<<endl; //输出顶点K与之对应的权值 cout<<"取出的顶点为:"<<k<<"将顶点"<<k<<"与顶点"<<closest[k]<<"相连"<<endl; lowcost[k] = 0; //将顶点K置于集合U中 for(j=2;j<=G->vexnum;j++) //调整数组lowcost和 cloest if(G->edge[k][j]<lowcost[j]){ lowcost[j] = G->edge[k][j]; closest[j] = k; } cout<<"将第"<<i<<"个元素放入集合U中时,Lowcost更新后的序列:"; for(h = 2;h<=G->vexnum;h++) cout<<lowcost[h]<<" "; cout<<endl; } } //时间复杂度O(n^2) //建立图的邻接矩阵 void createMTGraph(MTGraph *G){ int i,j,k,w; cout<<"输入顶点数和边数如(5 7)"<<endl; cin>>G->vexnum>>G->edgenum; cout<<"输入顶点信息,如(A B C D...)"<<endl; for(i = 0 ; i<G->vexnum;i++) cin>>G->verlist[i]; for(i = 0 ; i<=G->vexnum;i++) for(j = 0 ; j<=G->vexnum;j++) G->edge[i][j] = infinity; cout<<"输入边(i,j)上的权值w,如(i j w)"<<endl; for(k=0;k<G->edgenum;k++){ cin>>i>>j>>w; G->edge[i][j] = w; G->edge[j][i] = w; } } main(){ MTGraph *G ; G = new MTGraph(); createMTGraph(G); printMTGragh(G); Prim(G); system("pause"); }
程序运行后的结果
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-11 23:41:47