MST-kruskal ElogE+V
#include<stdio.h> #include<algorithm> using namespace std; struct dis { int a, b, c; } s[10010]; int cmp(dis x, dis y) { return x.c < y.c; } int father[110]; int fsize[110]; int findfather(int y) { int r = y; while (r != father[r]) { r = father[r]; } return r; } int combine(int a, int b) { int fx = findfather(a); int fy = findfather(b); if (fx != fy) { if (fsize[fx] >= fsize[fy]) { father[fy] = fx; fsize[fx] += fsize[fy]; fsize[fy] = 0; } else { father[fx] = fy; fsize[fy] += fsize[fx]; fsize[fx] = 0; } return 1; } else { return 0; } } int main() { int t, i, n, sum, m; while (~scanf("%d", &t), t) { n = t * (t - 1) / 2; for (i = 1; i <= t; i++) { fsize[i] = 1; father[i] = i; } for (i = 0; i < n; i++) { scanf("%d%d%d", &s[i].a, &s[i].b, &s[i].c); } sort(s, s + n, cmp); m = 1, sum = 0; for (i = 0; i < n && m < t; i++) { if (combine(s[i].a, s[i].b)) { m++; sum += s[i].c; } } printf("%d\n", sum); } return 0; }