标签:hdu2122
2 1 0 1 10 4 0
10 impossible
#include <stdio.h> #include <string.h> #include <algorithm> #define maxn 1002 #define maxm 10002 using std::sort; int pre[maxn], count, len; struct Node { int u, v, cost; } E[maxm]; int ufind(int k) { int a = k, b; while(pre[k] != -1) k = pre[k]; while(a != k) { b = pre[a]; pre[a] = k; a = b; } return k; } bool cmp(Node a, Node b) { return a.cost < b.cost; } void Kruskal(int m) { memset(pre, -1, sizeof(pre)); int u, v, i; len = 0; for(i = 0; i < m && count > 1; ++i) { u = ufind(E[i].u); v = ufind(E[i].v); if(u != v) { len += E[i].cost; pre[v] = u; --count; } } if(1 == count) printf("%d\n\n", len); else printf("impossible\n\n"); } int main() { int n, m, i; while(scanf("%d%d", &n, &m) == 2) { count = n; for(i = 0; i < m; ++i) scanf("%d%d%d", &E[i].u, &E[i].v, &E[i].cost); sort(E, E + m, cmp); Kruskal(m); } return 0; }
HDU2122 Ice_cream’s world III 【最小生成树】,布布扣,bubuko.com
HDU2122 Ice_cream’s world III 【最小生成树】
标签:hdu2122
原文地址:http://blog.csdn.net/chang_mu/article/details/38501547