此为《大话数据结构》提供,对排序算法进行补充。
//============================================================================
// Name : MST.cpp
// Author : Julie
// Version : 0.0.1
// Copyright : Julie@2015.02.10
// Description : To Generate the MST with Kruskal algorithm
//============================================================================
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define N 7
#define M 7
#define inf 10000
#define MAXEDGE 15
#define MAXVEX 7
struct Edge
{
int begin;
int end;
int weight;
};
typedef struct node
{
int matrix[N][M]; //邻接矩阵
int n; //顶点数
int e; //边数
}MGraph1;
int Find(int *parent, int f)
{
while (f < MAXVEX && parent[f] > 0)
{
f = parent[f];
}
return f;
}
bool cmp(Edge e1, Edge e2)
{
return e1.weight < e2.weight;
}
void MiniSpanTree_Kruskal(MGraph1 Mtest)
{
//Edge edges[MAXEDGE]; //定义边集数组
int parent[MAXVEX + 1]; //定义一数组用来判断边与边是否形成回路
//将邻接矩阵G转化为边集数组并按权由小到大排序
vector<Edge> edges1;
for (int i = 0; i < Mtest.n - 1; i++)
{
for (int j = 0; j < Mtest.n; j++)
{
if (Mtest.matrix[i][j] > 0)
{
Edge tmp_edge;
tmp_edge.begin = min(i, j);
tmp_edge.end = max(i, j);
tmp_edge.weight = Mtest.matrix[i][j];
edges1.push_back(tmp_edge);
}
}
}
sort(edges1.begin(), edges1.end(), cmp);
for (int i = 0; i < Mtest.n; i++)
{
parent[i] = 0;
}
for (int i = 0; i < Mtest.e; i++)
{
int n_edge = Find(parent, edges1.at(i).begin);
int m_edge = Find(parent, edges1.at(i).end);
if (n_edge != m_edge)
{
parent[n_edge] = m_edge;
cout << edges1.at(i).begin << " " << edges1.at(i).end << ":"
<< edges1.at(i).weight << endl;
}
}
}
int main()
{
MGraph1 MGraph;
MGraph.n = 7;
MGraph.e = 12;
int n1, n2;
for (int i = 0; i < MGraph.n; i++)
{
for (int j = 0; j < MGraph.n; j++)
MGraph.matrix[i][j] = -inf;
}
for (int i = 0; i < MGraph.e; i++){
cin >> n1 >> n2;
cin >> MGraph.matrix[n1][n2];
//MGraph.matrix[n2][n1] = MGraph.matrix[n1][n2];
}
MiniSpanTree_Kruskal(MGraph);
return 0;
}