#include <iostream>
#include <iomanip>
using namespace std;
#define MaxVertexNum 100 //最大頂點數
#define INFINTY 65535 //最大值
typedef char VertexType;
typedef int AdjType;
typedef struct {
VertexType vertex[MaxVertexNum]; //頂點向量
AdjType arcs[MaxVertexNum][MaxVertexNum]; //鄰接矩陣
int vexnum,arcnum; //圖的當前頂點數和弧數
}MGraph;
//求最小生成樹的輔助數組
typedef struct closedge{
VertexType adjvex; //記錄最小邊在U中的那個頂點
int lowcost; //存儲最小邊的權重
}Closedge[MaxVertexNum];
Closedge closedge;
int LocateVex(MGraph *G,VertexType v);
void CreateUDN(MGraph *G);
void Prim(MGraph *G,VertexType u);
void display(MGraph *G);
int main()
{
MGraph G;
CreateUDN(&G);
Prim(&G,'1');
return 0;
}
/*
1 2 6
1 3 1
1 4 5
2 3 5
2 5 3
3 4 5
3 5 6
3 6 4
4 6 2
5 6 6
*/
//以無向帶權圖爲例
void CreateUDN(MGraph *G)
{
VertexType v1,v2;
int weight;
//確定頂點數和弧數
cout<<"請輸入頂點數和邊數:";
cin>>G->vexnum>>G->arcnum;
//確定各個頂點的值
cout<<"請輸入各頂點的值:";
for(int i=0;i<G->vexnum;i++)
cin>>G->vertex[i];
//初始化鄰接矩陣
for (int i = 0; i < G->vexnum; ++i)
{
for(int j=0;j< G->vexnum;j++)
G->arcs[i][j] = INFINTY;
}
//確定鄰接矩陣
cout<<"請輸入"<<G->arcnum<<"對頂點和相應的權重:\n";
for(int k=0; k<G->arcnum; k++)
{
cin>>v1>>v2>>weight;
int i = LocateVex(G,v1);
int j = LocateVex(G,v2);
if(i>=0 && j>=0)
{
G->arcs[i][j] = weight;
G->arcs[j][i] = weight;
}
}
display(G);
}
//求頂點位置函數
int LocateVex(MGraph *G,VertexType v)
{
int i;
for(i=0;i<G->vexnum;i++)
{
if(G->vertex[i] == v)
return i;
}
return -1;
}
int Min(MGraph *G)
{
int k;
int min = INFINTY;
for(int i=0;i<G->vexnum;i++)
{
if(closedge[i].lowcost!=0 && closedge[i].lowcost<min)
{
min = closedge[i].lowcost;
k = i;
}
}
return k;
}
void Prim(MGraph *G,VertexType u)
{
int m,s=0;
VertexType v0,u0;
int k = LocateVex(G,u);
closedge[k].lowcost = 0; //講當前頂點加入生成樹中
//初始化V-U中的頂點的輔助數組(即開始頂點到其他各頂點的距離)
for(int i=0;i<G->vexnum;i++)
{
if(i!=k)
{
closedge[i].adjvex = u;
closedge[i].lowcost = G->arcs[k][i];
//cout<<"----------"<<closedge[i].lowcost<<endl;
}
}
//找n-1條邊
cout<<"最小生成樹的邊爲:"<<endl;;
for(int e=1;e<G->vexnum;e++)
{
m = Min(G);
u0 = closedge[m].adjvex;
v0 = G->vertex[m];
cout<<"("<<u0<<","<<v0<<")"<<endl;
s+=closedge[m].lowcost;
closedge[m].lowcost = 0;
//在 v0頂點加入U中之後,更新closedge[i](即更新生成樹到每一個非樹頂點的距離)
for (int i = 0; i < G->vexnum; i++)
{
if(G->arcs[m][i]<closedge[i].lowcost)
{
closedge[i].lowcost = G->arcs[m][i];
closedge[i].adjvex = v0;
}
}
}
cout<<"最小生成樹的權重之和爲:"<<s<<endl;
}
void display(MGraph *G)
{
cout<<"該圖對應的臨接矩陣爲:"<<endl;
for(int i=0;i<G->vexnum;i++)
{
for(int j=0;j<G->vexnum;j++)
{
cout<<setw(8)<<G->arcs[i][j];
}
cout<<endl;
}
}
最小生成樹算法(1)-----------prim
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.