测试数据1
按照上面的图例进行数据的输入。
请输入图的顶点数和边数:6 9
请输入顶点的值:0 1 2 3 4 5
请输入边的起点终点和权值:1 4 12
2 3 17
0 5 19
2 5 25
3 5 25
4 5 26
0 1 34
3 4 38
0 2 46
用Kruskal算法生成最小生成树的生成次序为:
(1,4)12
(2,3)17
(0,5)19
(2,5)25
(4,5)26
测试数据2
请输入图的顶点数和边数:3 3
请输入顶点的值:A B C
请输入边的起点终点和权值:A B 3
A C 12
B C 9
用Kruskal算法生成最小生成树的生成次序为:
(A,B)3
(B,C)9
#include<iostream>
using namespace std;
const int MAX = 100;
const int impossible = 0x7f7f7f7f; //初始化最小值为一个不可能的数值
struct edgeType
{
char from,to;
int weight;
};
class edgeGraph {
private:
char vertex[MAX];//顶点数组
edgeType edge[MAX];//边的数组
int vertexNum, edgeNum;
int Findroot(int parent[], int v);
public:
edgeGraph();
~edgeGraph(){}
void Kruskal();
int getIndex(char ch);
void Order();
};
edgeGraph::edgeGraph() {
cout << "请输入图的顶点数和边数:";
cin >> vertexNum >> edgeNum;
cout << "请输入顶点的值:";
for (int i = 0; i < vertexNum; i++) {
cin >> vertex[i];
}
cout << "请输入边的起点终点和权值:" << endl;
for (int j = 0; j < edgeNum; j++) {
char first, second;
int w;
cin >> first >> second >> w;
edge[j].from = first;
edge[j].to = second;
edge[j].weight = w;
}
}
void edgeGraph::Order() {
edgeType t;
for (int i = 0; i < edgeNum; i++) {
for (int j = 0; j < edgeNum-i; j++) {
if (edge[j].weight > edge[j + 1].weight) {
t = edge[j];
edge[j] = edge[j + 1];
edge[j + 1] = t;
}
}
}
return;
}
void edgeGraph::Kruskal() {
int parent[MAX];
int vex1, vex2;
for (int i = 0; i < vertexNum; i++) {
parent[i] = -1;
}
int num = 0;
for (int i = 0; i < edgeNum; i++) {
vex1 = Findroot(parent, getIndex(edge[i].from));
vex2 = Findroot(parent, getIndex(edge[i].to));
if (vex1 != vex2) {
cout << "(" << edge[i].from<< ","<<edge[i].to << ")" << edge[i].weight << endl;
parent[vex2] = vex1;
num++;
if (num == vertexNum - 1)
return;
}
}
}
int edgeGraph::Findroot(int parent[], int v) {//顶点v所在的集合的根
int t = v;
while (parent[t]>-1){
t = parent[t];
}
return t;
}
int edgeGraph::getIndex(char ch) {
for (int i = 0; i < vertexNum; i++) {
if (vertex[i] == ch) {
return i;
}
}
}
int main() {
edgeGraph g;
g.Order();
cout << "用Kruskal算法生成最小生成树的生成次序为:" << endl;
g.Kruskal();
return 0;
}