#include <iostream> #include <iomanip> using namespace std; #define MaxVertexNum 100 //最大顶点数 #define INFINTY 65535 //最大值 typedef char VertexType; typedef int AdjType; typedef struct { VertexType vertex[MaxVertexNum]; //顶点向量 AdjType arcs[MaxVertexNum][MaxVertexNum]; //邻接矩阵 int vexnum,arcnum; //图的当前顶点数和弧数 }MGraph; //求最小生成树的辅助数组 typedef struct closedge{ VertexType adjvex; //记录最小边在U中的那个顶点 int lowcost; //存储最小边的权重 }Closedge[MaxVertexNum]; Closedge closedge; int LocateVex(MGraph *G,VertexType v); void CreateUDN(MGraph *G); void Prim(MGraph *G,VertexType u); void display(MGraph *G); int main() { MGraph G; CreateUDN(&G); Prim(&G,'1'); return 0; } /* 1 2 6 1 3 1 1 4 5 2 3 5 2 5 3 3 4 5 3 5 6 3 6 4 4 6 2 5 6 6 */ //以无向带权图为例 void CreateUDN(MGraph *G) { VertexType v1,v2; int weight; //确定顶点数和弧数 cout<<"请输入顶点数和边数:"; cin>>G->vexnum>>G->arcnum; //确定各个顶点的值 cout<<"请输入各顶点的值:"; for(int i=0;i<G->vexnum;i++) cin>>G->vertex[i]; //初始化邻接矩阵 for (int i = 0; i < G->vexnum; ++i) { for(int j=0;j< G->vexnum;j++) G->arcs[i][j] = INFINTY; } //确定邻接矩阵 cout<<"请输入"<<G->arcnum<<"对顶点和相应的权重:\n"; for(int k=0; k<G->arcnum; k++) { cin>>v1>>v2>>weight; int i = LocateVex(G,v1); int j = LocateVex(G,v2); if(i>=0 && j>=0) { G->arcs[i][j] = weight; G->arcs[j][i] = weight; } } display(G); } //求顶点位置函数 int LocateVex(MGraph *G,VertexType v) { int i; for(i=0;i<G->vexnum;i++) { if(G->vertex[i] == v) return i; } return -1; } int Min(MGraph *G) { int k; int min = INFINTY; for(int i=0;i<G->vexnum;i++) { if(closedge[i].lowcost!=0 && closedge[i].lowcost<min) { min = closedge[i].lowcost; k = i; } } return k; } void Prim(MGraph *G,VertexType u) { int m,s=0; VertexType v0,u0; int k = LocateVex(G,u); closedge[k].lowcost = 0; //讲当前顶点加入生成树中 //初始化V-U中的顶点的辅助数组(即开始顶点到其他各顶点的距离) for(int i=0;i<G->vexnum;i++) { if(i!=k) { closedge[i].adjvex = u; closedge[i].lowcost = G->arcs[k][i]; //cout<<"----------"<<closedge[i].lowcost<<endl; } } //找n-1条边 cout<<"最小生成树的边为:"<<endl;; for(int e=1;e<G->vexnum;e++) { m = Min(G); u0 = closedge[m].adjvex; v0 = G->vertex[m]; cout<<"("<<u0<<","<<v0<<")"<<endl; s+=closedge[m].lowcost; closedge[m].lowcost = 0; //在 v0顶点加入U中之后,更新closedge[i](即更新生成树到每一个非树顶点的距离) for (int i = 0; i < G->vexnum; i++) { if(G->arcs[m][i]<closedge[i].lowcost) { closedge[i].lowcost = G->arcs[m][i]; closedge[i].adjvex = v0; } } } cout<<"最小生成树的权重之和为:"<<s<<endl; } void display(MGraph *G) { cout<<"该图对应的临接矩阵为:"<<endl; for(int i=0;i<G->vexnum;i++) { for(int j=0;j<G->vexnum;j++) { cout<<setw(8)<<G->arcs[i][j]; } cout<<endl; } }
原文地址:http://blog.csdn.net/huolang_vip/article/details/46537851