最小生成树kruskal
#include <iostream>using namespace std;
#define MAXSIZE 100
#define INFINITY 65535
typedef int ElemType;
typedef char VertexType;
typedef struct MGraph{
VertexType vertex;///顶点表
ElemType arc;///邻接矩阵,可看作边表
ElemType vertexNum, arcNum;///vertexNum是顶点数,arcNum是边数
};
typedef struct EdgeNode{
int begin;
int end;
int weight;
};
void CreateMGraph(MGraph *G) {
int i, j, k ,n;
cout << "输入边数和顶点数:";
cin >> G->arcNum >> G->vertexNum;
///输入顶点
cout << "输入顶点" << endl;
for (i = 0; i < G->vertexNum; i++) {
cin >> G->vertex;
}
///初始化矩阵
for (i = 0; i < G->vertexNum; i++) {
for (j = 0; j < G->vertexNum; j++) {
G->arc = G->arc = INFINITY;
G->arc = 0;
}
}
///输入由顶点构成的边
for (k = 0; k < G->arcNum; k++) {
cout << "请输入与边关联的两个顶点的序号和权值,例如( 1 2 34):" << endl;
cin >> i>>j>>n;
G->arc = n;
G->arc = G->arc;
}
}
///交换边集数组中的元素
void swap(EdgeNode edges[], int i ,int j){
int temp ;
temp = edges.begin;
edges.begin = edges.begin;
edges.begin = temp;
temp=edges.end;
edges.end = edges.end;
edges.end = temp;
temp = edges.weight;
edges.weight = edges.weight;
edges.weight = temp;
}
///排序
void Bubblesort(MGraph G,EdgeNode edges[]){
int i , j ;
for( i = 0 ; i < G.vertexNum; i++)
{
for(j = 0 ; j < G.vertexNum; j++)
{
if( edges.weight > edges.weight)
{
swap(edges,j,j+1);
}
}
}
}
int Find(int partent[],int f){
while( partent > 0)
{
f =partent;
}
return f;
}
void MiniSpanTree_Kruskal(MGraph G){
int i, j, n, m;
int k = 0;
int parent;
EdgeNode edges;
cout<<"起点"<<"\t"<<"终点"<<"\t"<<"权值"<<endl;
///将这个邻接矩阵变为边集数组
for( i = 0 ;i < G.vertexNum - 1;i++)
{
for(j = i + 1; j <G.vertexNum; j++)
{
if(G.arc < INFINITY)
{
edges.begin = i;
edges.end = j;
edges.weight=G.arc;
k++;
}
}
}
Bubblesort(G,edges);
/****************************/
///初始化数组
for(i = 0; i < G.vertexNum; i++)
{
parent = 0;
}
///打印最小生成树
for(i = 0;i < G.arcNum; i++)
{
n=Find(parent,edges.begin);
m=Find(parent,edges.end);
if( n != m) ///如果相等则说明形成了环状
{
parent = m;///partent第n(是起点)个位置存放终点坐标
cout<<edges.begin<<"\t"<<edges.end<<"\t"<<edges.weight<<endl;
}
}
}
int main() {
MGraph G;
CreateMGraph(&G);
MiniSpanTree_Kruskal(G);
return 0;
}
鉴于其他几个都要收费,我就免费给大家提供一段自己的代码,方便大家自己理解 22
6
QAQ 看 看看 Q {:5_91:} 321 1
11 学习学习 {:9_239:} 谢谢大佬 33
0 1 {:10_277:} 楼主费心了。 看看