HDOJ 1863 畅通工程
MST,kruskal,并查集,路径压缩;
参考白书的做法:另定义一个边序号数组,排序时按照边权的大小排;
1A,表示已经对WA,TLE,RE等过敏,一提交心里就发毛啊……
代码有点长,重新回到 CB 不太适应。
# include <stdio.h> # include <stdlib.h> # define MAXN 105 int n, m; int w[MAXN], u[MAXN], v[MAXN], r[MAXN], p[MAXN]; int kruskal(void); int cmp(const void *x, const void *y){return (w[*(int*)x]<w[*(int*)y] ? -1:1);} int find(int x){return p[x]==x ? x:(p[x] = find(p[x]));} int main() { int i, ans; while (~scanf("%d%d", &n, &m)) { if (!n) break; for (i = 1; i <= n; ++i) { r[i] = i; scanf("%d%d%d", &u[i], &v[i], &w[i]); } if (n < m-1) {puts("?"); continue;} for (i = 1; i <= m; ++i) p[i] = i; ans = kruskal(); if (ans > 0) printf("%d\n", ans); else puts("?"); } return 0; } int kruskal(void) { int i, cost, cnt, x, y, t; cnt = 0; cost = 0; qsort(r+1, n, sizeof(int), cmp); for (i = 1; i <= n; ++i) { t = r[i]; x = find(u[t]); y = find(v[t]); if (x != y) { ++cnt; cost += w[t]; p[x] = y; } } return cnt==m-1 ? cost:-1; }