用kruskal算法求最小生成树c语言完整代码,节点为字母
时间: 2024-03-22 22:42:09 浏览: 69
下面是用C语言实现Kruskal算法求最小生成树的完整代码,节点为字母:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXN 100
#define INF 0x3f3f3f3f
typedef struct Edge {
int u, v, w;
} Edge;
int n, m;
Edge edges[MAXN * MAXN];
int father[MAXN];
int rank[MAXN];
int cmp(const void *a, const void *b) {
return ((Edge *)a)->w - ((Edge *)b)->w;
}
int find(int x) {
if (father[x] == x) {
return x;
}
return father[x] = find(father[x]);
}
void unite(int x, int y) {
int fx = find(x), fy = find(y);
if (rank[fx] < rank[fy]) {
father[fx] = fy;
} else {
father[fy] = fx;
if (rank[fx] == rank[fy]) {
rank[fx]++;
}
}
}
int kruskal() {
int ans = 0;
qsort(edges, m, sizeof(Edge), cmp);
for (int i = 0; i < n; i++) {
father[i] = i;
rank[i] = 0;
}
for (int i = 0; i < m; i++) {
int u = edges[i].u, v = edges[i].v, w = edges[i].w;
if (find(u) != find(v)) {
unite(u, v);
ans += w;
}
}
return ans;
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i < m; i++) {
char u, v;
int w;
scanf(" %c%c%d", &u, &v, &w);
edges[i].u = u - 'A';
edges[i].v = v - 'A';
edges[i].w = w;
}
int ans = kruskal();
printf("%d\n", ans);
return 0;
}
```
其中,`cmp`函数是用于排序的比较函数,`find`函数是并查集的查找函数,`unite`函数是并查集的合并函数。在`main`函数中,先读入节点数和边数,然后读入每条边的起点、终点和权值,最后调用`kruskal`函数求解最小生成树的权值和。
阅读全文