按照课件的思路整合的代码,哈哈
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
#define MaxValue 32700
const int NumEdges = 50; //边条数
const int NumVertices = 10; //顶点个数
typedef char VertexData; //顶点数据类型
typedef int EdgeData; //边上权值类型
typedef struct {
//VertexData vexList[NumVertices]; //顶点表
EdgeData Edge[NumVertices][NumVertices];
//邻接矩阵, 可视为边之间的关系
int n, e; //图中当前的顶点个数与边数
} MTGraph;
typedef struct {
int head,tail;
int cost;
} MST;
MST T[100];
void Prim ( MTGraph G, MST T[] ,int u ) {
double lowcost[G.n];
int nearvex[G.n];
for ( int i = 0; i < G.n; i++ ) {
lowcost[i] = G.Edge[u][i]; //Vu到各点代价
nearvex[i] = u; //及最短带权路径
}
nearvex[u] = -1; //加到生成树顶点集合
int k = 0; //存放最小生成树结点的变量
for ( int i = 0; i < G.n; i++ ) {
if ( i != u ) { //循环n-1次, 加入n-1条边
EdgeData min = MaxValue;
int v = 0;
for ( int j = 0; j < G.n; j++ ) {
if ( nearvex[j] != -1 && // =-1不参选
lowcost[j] < min ) {
v = j;
min = lowcost[j];
}
//求生成树外顶点到生成树内顶点具有最
//小权值的边, v是当前具最小权值的边
}
if ( v ) { //v=0表示再也找不到要求顶点
T[k].tail = nearvex[v]; //选边加入生成树
T[k].head = v;
T[k++].cost = lowcost[v];
nearvex[v] = -1; //该边加入生成树标记
for ( int j = 0; j < G.n; j++ )
if ( nearvex[j] != -1 &&
G.Edge[v][j] < lowcost[j] ) {
lowcost[j] = G.Edge[v][j]; //修改
nearvex[j] = v;
}
}
} //循环n-1次, 加入n-1条边
}
}
int main() {
MTGraph G;
int s,t,path;
cout<<"请输入顶点个数"<<endl;
cin>>G.n;
cout<<"请输入边数"<<endl;
cin>>G.e;
for(int i=0; i<G.n; i++) {
for(int j=0; j<G.n; j++) {
if(i==j) G.Edge[i][j]=0;
else G.Edge[i][j]=MaxValue;
}
}
cout<<"请输入各边权值"<<endl;
for(int i=1; i<=G.e; i++) {
cin>>s>>t>>path;
G.Edge[s][t]=G.Edge[t][s]=path;
}
Prim(G,T,0);
cout<<endl;
for(int i=0;i<G.n-1;i++){
cout<<T[i].head<<" "<<T[i].tail<<" "<<T[i].cost<<endl;
}
return 0;
}
/*
0 1 28
1 2 16
2 3 12
3 4 22
4 5 25
5 0 10
4 6 24
3 6 18
1 6 14
*/