最小生成树和Kruskal算法
源代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define MAXV 100
#define MaxSize 100
#define INF 65535
typedef struct{
int edges[MAXV][MAXV];//领接矩阵数组
int n, e;//顶点数,边数
} MatGraph;
typedef struct{
int u;//边的起始顶点
int v;//边的终止顶点
int w;//边的权值
} Edge;
int cmp( const void *a ,const void *b)
{
return (*(Edge *)a).w > (*(Edge *)b).w ? 1 : -1;
}
void Kruskal(MatGraph g){
int i, j, u1, v1, sn1, sn2, k;
Edge E[MaxSize];
int vset[MAXV];
k = 0;
for (i = 0; i < g.n;i++){
for (j = 0; j <= i;j++){
if(g.edges[i][j]>0&&g.edges[i][j]<INF){
E[k].u = i;
E[k].v = j;
E[k].w = g.edges[i][j];
k++;
}
}
}
qsort(E, k, sizeof(E[0]), cmp);//快排,需要定义cmp()函数
for (i = 0; i < g.n;i++){
vset[i] = i;
}
k = 1;
j = 0;
while(k<g.n){
u1 = E[j].u;
v1 = E[j].v;
sn1 = vset[u1];
sn2 = vset[v1];
if(sn1!=sn2){
printf("(%d,%d):%d\n", u1+1, v1+1, E[j].w);
k++;
for (i = 0; i < g.n;i++){
if(vset[i]==sn2){
vset[i] = sn1;
}
}
}
j++;
}
}
int main(void){
FILE *pBanana;
int i, j, w;
bool dog[MAXV];
MatGraph *apple = (MatGraph *)malloc(sizeof(MatGraph));
if(apple==NULL){
return 1;
}
memset((*apple).edges,INF,MAXV * MAXV * sizeof(int));
memset(dog, false, sizeof(bool) * MAXV);
(*apple).n = 0;
(*apple).e = 0;
pBanana = fopen("cat.txt", "r");
while(!feof(pBanana)){
fscanf(pBanana, "%d\t%d\t%d", &i, &j, &w);
if(dog[i-1]==false){
(*apple).n++;
dog[i-1] = true;
}
(*apple).e++;
(*apple).edges[i-1][j-1] = w;
fgetc(pBanana);
}
(*apple).e /= 2;
fclose(pBanana);
Kruskal(*apple);
getchar();//两个getchar()方便查看窗口
getchar();
return 0;
}
cat.txt
1 2 6
2 1 6
1 3 1
3 1 1
1 4 5
4 1 5
2 5 3
5 2 3
2 3 5
3 2 5
3 4 5
4 3 5
3 5 6
5 3 6
3 6 4
6 3 4
4 6 2
6 4 2
5 6 6
6 5 6
运行结果