最小生成树 之 CODE[VS] 1231 最优布线问题

/*
  最小生成树 之 CODE[VS] 1231 最优布线问题
  Kruskal算法(邻接表)
*/
  1 #include <iostream>
  2 #include <cstdlib>
  3 #include <cstdio>
  4 #include <cstddef>
  5 #include <iterator>
  6 #include <algorithm>
  7 #include <string>
  8 #include <locale>
  9 #include <cmath>
 10 #include <vector>
 11 #include <cstring>
 12 #include <map>
 13 #include <utility>
 14 #include <queue>
 15 #include <stack>
 16 #include <set>
 17 #include <functional>
 18 using namespace std;
 19 typedef pair<int, int> PII; 
 20 typedef long long int64;
 21 const int INF = 0x3f3f3f3f;
 22 const int modPrime = 3046721;
 23 const double eps = 1e-9;
 24 const int MaxN = 100010;
 25 const int MaxM = 100010;
 26 
 27 
 28 
 29 /***************************************************/
 30 /*Union-find sets*/
 31 int ftr[MaxN];
 32 int rnk[MaxN];
 33 
 34 void ufsIni(int n)
 35 {
 36     for (int i = 0; i <= n; ++i)
 37     {
 38         ftr[i] = i;
 39         rnk[i] = 0;
 40     }
 41 }
 42 
 43 int ufsFind(int x)
 44 {
 45     if (x == ftr[x]) return x;
 46     return ftr[x] = ufsFind(ftr[x]);
 47 }
 48 
 49 void ufsUnion(int x, int y)
 50 {
 51     x = ufsFind(x);
 52     y = ufsFind(y);
 53     if (x == y) return;
 54 
 55     if (rnk[x] < rnk[y])
 56     {
 57         ftr[x] = y;
 58     }
 59     else
 60     {
 61         ftr[y] = x;
 62         if (rnk[x] == rnk[y])
 63         {
 64             ++rnk[x];
 65         }
 66     }
 67 }
 68 
 69 bool ufsSame(int x, int y)
 70 {
 71     return (ufsFind(x) == ufsFind(y));
 72 }
 73 
 74 /***************************************************/
 75 
 76 int N, M;
 77 struct Edge
 78 {
 79     int u, v, cost;
 80 };
 81 
 82 bool Cmp(const Edge e1, const Edge e2)
 83 {
 84     return e1.cost < e2.cost;
 85 }
 86 Edge edge[MaxM];
 87 
 88 
 89 void Solve()
 90 {
 91     ufsIni(N);
 92     sort(edge, edge + M, Cmp);
 93     int64 ans = 0;
 94     for (int i = 0; i < M; ++i)
 95     {
 96         Edge eg = edge[i];
 97         if (!ufsSame(eg.u, eg.v))
 98         {
 99             ufsUnion(eg.u, eg.v);
100             ans += eg.cost;
101         }
102     }
103     printf("%lld\n", ans);
104 }
105 
106 int main()
107 {
108 #ifdef HOME
109     freopen("in", "r", stdin);
110     //freopen("out", "w", stdout);
111 #endif
112 
113     scanf("%d %d", &N, &M);
114     for (int i = 0; i < M; ++i)
115     {
116         scanf("%d %d %d", &edge[i].u, &edge[i].v, &edge[i].cost);
117     }
118 
119     Solve();
120 
121 #ifdef HOME
122     cerr << "Time elapsed: " << clock() / CLOCKS_PER_SEC << " ms" << endl;
123     _CrtDumpMemoryLeaks();
124 #endif
125     return 0;
126 }

 

 
posted @ 2015-12-16 21:34  JmingS  阅读(255)  评论(0编辑  收藏  举报