设N=(V,{E})是连通网
1)令最小生成树的初始状态为只有n个顶点而无边的非连通图T=(V, {}),图中每个顶点自成一个连通分量;
2) 在E中选择代价最小的边,若该边依附的顶点落在T中不同的连通分量上,则将此边加入到T中,否则舍去此边而选择下一条代价最小的边 ;
3)反复执行第2)步,直至T中所有顶点都在同一连通分量上为止。
则T=(V, {TE})为N的最小生成树。
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#define MAX 20
using namespace std;
typedef struct{
int data;
int jihe;
}VexNode;
typedef struct{
int vexh,vext;
int weight;
}EdgeNode;
int cmp(EdgeNode A, EdgeNode B){
return A.weight < B.weight;
}
void Kruskal(EdgeNode e[], int vexnum, int arcnum){
VexNode vex[MAX];
int i;
for(i = 1; i <= vexnum; i ++){
vex[i - 1].data = vex[i - 1].jihe = i;
}
int m1,m2,n1,n2,j,k = 1;
i = 0;
printf("\n=====华丽分割线=====\n");
while(k < vexnum){
m1 = e[i].vexh; m2 = e[i].vext;
n1 = vex[m1- 1].jihe; n2 = vex[m2 - 1].jihe;
if(n1 != n2){
printf("%d %d %d\n",m1,m2,e[i].weight);
k ++;
for(j = 0; j < vexnum; j ++){
if(n2 == vex[j].jihe)
vex[j].jihe = n1;
}
}
i ++;
}
}
int main(){
EdgeNode e[MAX];
int vexnum,arcnum;
scanf("%d%d",&vexnum,&arcnum);
for(int i = 0; i < arcnum; i ++){
scanf("%d%d%d",&e[i].vexh,&e[i].vext,&e[i].weight);
}
sort(e,e+arcnum,cmp);
Kruskal(e,vexnum,arcnum);
return 0;
}