普里姆算法(最小生成树)

#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;
	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);
	for(j=0; j<G.vexnum; j++)
	{
		closedge[j].adjvex=u;
		closedge[j].lowcost=G.arcs[k][j];

	}
	closedge[k].lowcost=0;
	cout<<"最小生成树各边为:"<<endl;

	for(i=1; i<G.vexnum; i++)
	{
		k=minimum(closedge, G);
		cout<<closedge[k].adjvex<<"-"<<G.vexs[k]<<endl;

		closedge[k].lowcost=0;
		for(j=0; j<G.vexnum; j++)
		{
			if(G.arcs[k][j] < closedge[j].lowcost)
			{
				closedge[j].adjvex=G.vexs[k];
				closedge[j].lowcost=G.arcs[k][j];
			}
		}
	}
}

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


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值