普利姆算法(prim)

#include <iostream>
#include <string>
using namespace std;

typedef struct MGraph {
	string vexs[10];//顶点信息
	int arcs[10][10];//邻接矩阵
	int vexnum, arcnum;
} MGraph;

typedef struct Closedge {
	string adjvex;    //最小边u中的那个顶点
	int lowcost;     //最小边上的权值
} minside[10];


int LocateVex(MGraph G, string u) { //返回顶点u在图中的位置
	for(int i=0; i<G.vexnum; i++)
		if(G.vexs[i]==u)
			return i;
	return -1;
}

void CreateUDG(MGraph &G) { //构造无向图
	string v1, v2;
	int w;
	int i, j, k;
	cout<<"请输入顶点数和边数:";
	cin>>G.vexnum>>G.arcnum;

	cout<<"请输入顶点:";
	for(i=0; i<G.vexnum; i++)
		cin>>G.vexs[i];

	for(i=0; i<G.vexnum; i++)
		for(j=0; j<G.vexnum; j++)
			G.arcs[i][j]=1000;

	cout<<"请输入边和权值:"<<endl;
	for(k=0; k<G.arcnum; k++) {
		cin>>v1>>v2>>w;
		i=LocateVex(G, v1);
		j=LocateVex(G, v2);
		G.arcs[i][j]=G.arcs[j][i]=w;
	}
}

int minimum(minside sz, MGraph G) { //求sz中lowcost的最小值,返回序号
	int i=0, j, k, min;
	while(!sz[i].lowcost)
		i++;
	min=sz[i].lowcost;
	k=i;
	for(j=i+1; j<G.vexnum; j++) {
		if(sz[j].lowcost>0 && min>sz[j].lowcost) {
			min=sz[j].lowcost;
			k=j;
		}
	}

	return k;

}

void MiniSpanTree_PRIM(MGraph G, string u) { //普里姆算法
	int i, j, k;
	minside closedge;
	k=LocateVex(G, u);                  //k为顶点u的下标
	for(j=0; j<G.vexnum; j++) { //对V-U的每一个顶点Vj初始化 closedge[j];
		if(j!=k) {
			closedge[j].adjvex=u;
			closedge[j].lowcost=G.arcs[k][j];
		}
	}
	closedge[k].lowcost=0;
	cout<<"最小生成树各边为:"<<endl;

	for(i=1; i<G.vexnum; i++) {                //选择其余n-1个顶点,生成n-1条边
		k=minimum(closedge, G);    //求出最小生成树T的下一个结点:第k个顶点,closedge[k]中存有当前最小边
		cout<<closedge[k].adjvex<<"-"<<G.vexs[k]<<endl;  //输出当前的最小边

		closedge[k].lowcost=0;                          //第k个顶点并入U集合
		for(j=0; j<G.vexnum; j++) {
			if(G.arcs[k][j] < closedge[j].lowcost) {    //新顶点并入U后,重新选择最小边
				closedge[j].adjvex=G.vexs[k];
				closedge[j].lowcost=G.arcs[k][j];
			}
		}
	}
}

int main() {
	MGraph g;
	CreateUDG(g);
	MiniSpanTree_PRIM(g, g.vexs[0]);
	cout<<endl;

}

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值