Kruskal
#include "iostream" #include "algorithm" using namespace std; #define MAXN 1111 struct node { int x, y, l; }p[MAXN]; int fa[MAXN]; int n, m, k; int re, num; bool cmp(node a, node b) { return a.l < b.l; } int findset(int x) { if (fa[x] == x) return x; return fa[x] = findset(fa[x]); } void merg(int x, int y) { int fx = findset(x); int fy = findset(y); if (fx != fy) fa[fy] = fx; } void init(int n) { for (int i = 0; i <= n; ++i) fa[i] = i; num = 0; re = 0; } int main() { int n, w, t; char ch, z; while (cin >> n, n) { init(n); for (int i = 1; i < n; ++i) { cin >> z >> t; z -= 'A'; for (int j = 0; j < t; ++j) { cin >> ch; cin >> w; p[num].x = z; p[num].y = ch - 'A'; p[num++].l = w; } } sort(p, p + num, cmp); for (int i = 0; i < num; ++i) { int x = findset(p[i].x); int y = findset(p[i].y); if (x != y) { fa[y] = x; re += p[i].l; } } cout << re << endl; } return 0; }