ZOJ-1406

来源:互联网 发布:java项目打包成war 编辑:程序博客网 时间:2024/06/07 15:23

经典纯最小生成树,用kruskal解的,感觉比Prim好写,可以做为以后Kruskal算法模板了

#include<stdio.h>#include<stdlib.h>struct Village{char name;struct Village *parent;int rank;};struct Road{struct Village *u;struct Village *v;int cost;};static struct Village *make_set(char c){struct Village *v = malloc(sizeof(struct Village));v->name = c;v->parent = v;v->rank = 0;return v;}static struct Village *find_set(struct Village *v){if (v->parent != v)v->parent = find_set(v->parent);return v->parent;}void link(struct Village *u, struct Village *v){if (u->rank > v->rank)v->parent = u;else{u->parent = v;if (u->rank == v->rank)v->rank++;}}void union_set(struct Village *u, struct Village *v){link(find_set(u), find_set(v));}static int cmp(const void *p1, const void *p2){struct Road *r1 = (struct Road*) p1;struct Road *r2 = (struct Road*) p2;return r1->cost - r2->cost;}int main(){int n;while (scanf("%d", &n), n){getchar();struct Village **array = malloc(n * sizeof(struct Village *));struct Road *roads = malloc(75 * sizeof(struct Road));int i, j, m, cost, index = 0;char s[2], t[2];for (i = 0; i < n; i++)array[i] = make_set('A' + i);for (i = 0; i < n - 1; i++){scanf("%s %d", s, &m);for (j = 0; j < m; j++){scanf("%s %d", t, &cost);roads[index].u = array[s[0] - 'A'];roads[index].v = array[t[0] - 'A'];roads[index].cost = cost;index++;}getchar();}qsort(roads, index, sizeof(struct Road), cmp);int sum = 0;for (i = 0; i < index; i++)if (find_set(roads[i].u) != find_set(roads[i].v)){union_set(roads[i].u, roads[i].v);sum += roads[i].cost;}printf("%d\n", sum);free(roads);free(array);}return 0;}


0 0