最小生成树算法(1)-----------prim
2015-06-17 20:33
239 查看
#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; } }
相关文章推荐
- pci设备学习笔记
- 进程间通信概述
- Python 装饰器
- Android-menu
- SQL中如何才能将查询的结果数据存在一个变量中???
- Spring IOC AOP详解(一)
- sharepoint 2013 配件控制FileUpload如何检查是否图像的方法
- 团队开发------第一次冲刺第3天
- Menu的三个实现方式
- 第15周-阅读项目1-异常处理&&命名空间
- 正则表达式
- IOS笔记050-事件处理
- 扩展C#与元编程(二)
- 提交游戏到AppStore被打回
- 删除 ComponentFamilies 下的子键和 f256! 值
- C#操作Excel文件(读取Excel,写入Excel)
- SHFileOperation实现拷贝进度条
- 软件测试演义——中高级系列(序)
- socket
- 多线程03-NSOperationQueue(掌握)