克魯斯卡爾算法
#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<<"請(qǐng)輸入總頂點(diǎn)數(shù),總邊數(shù),以空格隔開(kāi):";
cin>>G.vexnum>>G.arcnum;
cout>>endl;
cout<<"輸入點(diǎn)的名稱(chēng),如a"<<endl;
for(i=0;i<G.vexnum;++i){
cout<<"請(qǐng)輸入第"<<(i+1)<<"個(gè)點(diǎn)的名稱(chēng):";
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<<"輸入邊依附的頂點(diǎn)及權(quán)值,如a b 6"<<endl;
for(k=0;k<G.arcnum;++k){
VerTexType v1,v2;
ArcType w;
cout<<"請(qǐng)輸入第"<<(k+1)<<"條邊依附的頂點(diǎn)及權(quán)值:";
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];
//關(guān)鍵之所在,判斷是都構(gòu)成環(huán)
if(vs1!=vs2){
cout<<Edge[i].Head<<""<<Edge[i].Tail<<endl;
//關(guān)鍵之所在,合并后就可以判斷是否構(gòu)成環(huán)了
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<<"無(wú)向網(wǎng)G創(chuàng)建完成!"<<endl;
cout<<endl;
MinSpanTree_Kruskal(G);
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。