Tranvick

MST

Mar 31st, 2014
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.73 KB | None | 0 0
  1. #include <cstdio>
  2. #include <algorithm>
  3.  
  4. const int M = 2222222;
  5. const int N = 111111;
  6.  
  7. struct Edge {
  8.     int u, v, weight;
  9.     bool operator< (const Edge & q) const {
  10.         return weight < q.weight;
  11.     }
  12. } t[M];
  13.  
  14. int p[N], n, m, ans;
  15.  
  16. int find_set(int x) {
  17.     if (x == p[x]) {
  18.         return x;
  19.     } else {
  20.         return p[x] = find_set(p[x]);
  21.     }
  22. }
  23.  
  24. void unite(const Edge & e) {
  25.     int u = find_set(e.u);
  26.     int v = find_set(e.v);
  27.     if (u != v) {
  28.         p[u] = v;
  29.         ans += e.weight;
  30.     }
  31. }
  32.  
  33. int main() {
  34.     scanf("%d%d", &n, &m);
  35.     for (int i = 1; i <= n; ++i) {
  36.         p[i] = i;
  37.     }
  38.     for (int i = 0; i < m; ++i) {
  39.         scanf("%d%d%d", &t[i].u, &t[i].v, &t[i].weight);
  40.     }
  41.     std::sort(t, t + m);
  42.     for (int i = 0; i < m; ++i) {
  43.         unite(t[i]);
  44.     }
  45.     return 0;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment