克鲁斯卡尔算法
#include <iostream>
using namespace std;
typedef char VerTexType;
typedef int ArcType;
#define MVNum 100
#define MaxInt 32767
typedef struct{
VerTexType vexs[MVNum];
ArcType arcs[MVNum][MVNum];
int vexnum,arcnum;
}AMGraph;
struct{
VerTexType Head;
VerTexType Tail;
ArcType lowcost;
}Edge[(MVNum-(MVNum-1))/2];
int Vexset[MVNum];
int loacteVex(AMGraph G,VerTexType v){
for(int i=0;i<G.vexnum;++i)
if(G.vexs[i]==v)
return i;
return -1;
}
void CreateUDN(AMGraph &G){
int i,j,k;
cout<<"请输入总顶点数,总边数,以空格隔开:";
cin>>G.vexnum>>G.arcnum;
cout>>endl;
cout<<"输入点的名称,如a"<<endl;
for(i=0;i<G.vexnum;++i){
cout<<"请输入第"<<(i+1)<<"个点的名称:";
cin>>G.vexs[i];
}
cout<<endl;
for(i=0;i<G.vexnum;++i)
for(j=0;;j<G.vexnum;++i)
G.arcs[i][j]=MaxInt;
cout<<"输入边依附的顶点及权值,如a b 6"<<endl;
for(k=0;k<G.arcnum;++k){
VerTexType v1,v2;
ArcType w;
cout<<"请输入第"<<(k+1)<<"条边依附的顶点及权值:";
cin>>v1>>v2>>w;
i=loacteVex(G,v1);
j=loacteVex(G,v2);
G.arcs[i][j]=w;
G.arcs[j][i]=G.arcs[i][j];
Edge[k].lowcost=w;
Edge[k].Head=v1;
Edge[k].Tail=v2;
}
}
void Sort(AMGraph G){
int m=G.arcnum-2;
int flag=1;
while((m>0)&&flag==1){
flag=0;
for(int j=0;j<=m;j++){
if(Edge[j].lowcost>Edge[j+1].lowcost){
flag=1;
VerTexType temp_Head=Edge[j].Head;
Edge[j].Head=Edge[j+1].Head;
Edge[j+1].Head=temp_Head;
ArcType temp_lowcast=Edge[j].lowcost;
Edge[j].lowcost=Edge[j+1].lowcost;
Edge[j+1].lowcost=temp_lowcast;
}
}
--m;
}
}
void MinSpanTree_Kruskal(AMGraph G){
int i,j,v1,v2,vs1,vs2;
Sort(G);
for(i=0;i<G.vexnum;++i){
Vexset[i]=i;
}
for(i=0;i<G.arcnum;++i){
v1=loacteVex(G,Edge[i].Head);
v2=loacteVex(G,Edge[i].Tail);
vs1=Vexset[v1];
vs2=Vexset[v2];
//关键之所在,判断是都构成环
if(vs1!=vs2){
cout<<Edge[i].Head<<""<<Edge[i].Tail<<endl;
//关键之所在,合并后就可以判断是否构成环了
for(j=0;j<G.vexnum;++i)
if(Vexset[j]==vs2)
Vexset[j]=vs1;
}
}
}
void main(){
cout<<"克鲁斯卡尔算法"<<endl;
AMGraph G;
CreateUDN(G);
cout<<endl;
cout<<"无向网G创建完成!"<<endl;
cout<<endl;
MinSpanTree_Kruskal(G);
}