1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | int n; const int maxn = 110; struct Edge{ int u,v; long long c; bool operator < ( const Edge & a) const { return c < a.c; } }e[maxn*maxn/2]; int fa[maxn]; void ini( int n){ for ( int i = 0;i < n + 5;i++) fa[i] = i; } int fnd( int x){ return x == fa[x] ? x : (fa[x] = fnd(fa[x])); } int kruskal(){ sort(e,e + n*(n-1)/2); int ct = 0; long long res = 0; ini(n); for ( int i = 0;i < n*(n-1)/2;i++) { if (ct == n - 1) break ; int u = e[i].u,v = e[i].v; u = fnd(u); v = fnd(v); if (u != v){ fa[u] = v; res += e[i].c; ct++; } } return res; } |
原文:http://www.cnblogs.com/qhy285571052/p/5164766.html