#include <iostream>
#include<bits/stdc++.h>
using namespace std;
typedef struct{
int vexs[10];
int arcs[10][10];
int vnum;
}MGraph;
struct{
int adjvex;
int lowcost;
}closedge[100];
void creatAdjmatrix(MGraph &g){
int n,i,j;
cin>>n;
g.vnum=n;
for(i=1;i<=n;i++){
g.vexs[i]=i;
for(j=1;j<=n;j++){
g.arcs[i][j]=1000;
}
}
cin>>i>>j>>n;
while(i!=0&&j!=0){
g.arcs[i][j]=n;
g.arcs[j][i]=n;
cin>>i>>j>>n;
}
}
void MiniSpanTree_Prim(MGraph g,int u){
int num=1;
for(int i=1;i<=g.vnum;i++){
if(i!=u) closedge[i]={u,g.arcs[u][i]};
}
closedge[u].lowcost=0;
for(int i=1;i<g.vnum;i++){
int min,k;
for(int j=1;j<=g.vnum;j++){
if(closedge[j].lowcost!=0){
min=closedge[j].lowcost;
k=j;
break;
}
}
for(int j=1;j<=g.vnum;j++){
if(closedge[j].lowcost!=0&&closedge[j].lowcost<min){
min=closedge[j].lowcost;
k=j;
}
}
cout<<"第"<<num++<<"条边:"<<closedge[k].adjvex<<" "<<k<<endl;
closedge[k].lowcost=0;
for(int j=1;j<=g.vnum;j++){
if(g.arcs[k][j]<closedge[j].lowcost){
closedge[j].lowcost=g.arcs[k][j];
closedge[j].adjvex=k;
}
}
}
}
int main()
{
MGraph g;
creatAdjmatrix(g);//6 1 2 6 1 3 1 1 4 5 2 3 5 3 4 5 2 5 3 5 3 6 5 6 6 3 6 4 4 6 2 0 0 0
MiniSpanTree_Prim(g,1);
return 0;
}
最小生成树 加点法 Prim算法
最新推荐文章于 2023-01-28 23:41:05 发布