#include <iostream>
#include<bits/stdc++.h>
using namespace std;
typedef struct{
int vexs[10];
int arcs[10][10];
int vnum;
int arcnum;
}MGraph;
typedef struct d{
int head;
int tail;
int lowcost;
}edgeg;
edgeg edge[100];
void creatAdjmatrix(MGraph &g){
int n,i,j,arcnum=1;
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;
edge[arcnum].head=i;
edge[arcnum].tail=j;
edge[arcnum].lowcost=n;
arcnum++;
cin>>i>>j>>n;
}
g.arcnum=arcnum-1;
}
bool comparison(edgeg a,edgeg b){
return a.lowcost<b.lowcost;
}
void MiniSpanTree_Kruskal(MGraph g){
int vexset[100];
int num=1;
for(int i=1;i<=g.vnum;i++){
vexset[i]=i;
}
sort(edge+1,edge+g.arcnum+1,comparison);
//for(int i=1;i<=g.arcnum;i++)
// cout<<edge[i].head<<edge[i].tail<<edge[i].lowcost<<" ";
for(int i=1;i<=g.arcnum;i++){
int v1=edge[i].head;
int v2=edge[i].tail;
int vs1=vexset[v1];
int vs2=vexset[v2];
if(vexset[v1]!=vexset[v2]){
cout<<"第"<<num++<<"条边:"<<v1<<" "<<v2<<endl;
for(int j=1;j<=g.vnum;j++){
if(vexset[j]==vs2) vexset[j]=vs1;
}
}
}
}
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_Kruskal(g);
return 0;
}
克鲁斯卡尔算法 加边法构造最小生成树
最新推荐文章于 2024-02-09 15:57:53 发布