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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| #include <cstdio> #include <iostream> #include <algorithm> #include <cstring> using namespace std; #define MAXN 10000
int n, m, ans; int father[MAXN]; int ranks[MAXN];
struct Edge{ int from; int to; int cost; }edge[MAXN];
bool cmp(Edge e1, Edge e2) { return e1.cost < e2.cost; }
void init_set() { for(int i = 0; i < MAXN; i++){ father[i] = i; ranks[i] = 1; } }
int find_set(int x) { return father[x] == x ? father[x] : father[x] = find_set(father[x]); }
void union_set(int x, int y) { if(ranks[x] >= ranks[y]){ ranks[x] += ranks[y]; father[y] = x; } else{ ranks[y] += ranks[x]; father[x] = y; } }
void kruskal() { init_set(); int allcost = 0; sort(edge, edge + ans, cmp); for(int i = 0; i < ans; i++){ int root_x = find_set(edge[i].from); int root_y = find_set(edge[i].to); if(root_x != root_y){ union_set(root_x, root_y); allcost += edge[i].cost; } } printf("%d\n", allcost); }
int main() { freopen("input.txt", "r", stdin); int a; while(scanf("%d", &n) != EOF){ ans = 0; for(int i = 1; i <= n; i++){ for(int j = 1; j <= n; j++){ scanf("%d", &a); if(j > i){ edge[ans].from = i; edge[ans].to = j; edge[ans++].cost = a; } } } kruskal(); } return 0; }
|