Advertisement
tuki2501

qbmst.cpp

Nov 12th, 2021
1,204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.96 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct DSU {
  5.   int n; vector<int> root, hang;
  6.   DSU(int n): n(n), root(n + 1), hang(n + 1) {
  7.     for (int i = 1; i <= n; i++) {
  8.       root[i] = i;
  9.       hang[i] = 1;
  10.     }
  11.   }
  12.   int find(int i) {
  13.     if (i == root[i]) return i;
  14.     return root[i] = find(root[i]);
  15.   }
  16.   bool unite(int u, int v) {
  17.     u = find(u); v = find(v);
  18.     if (u == v) return false;
  19.     if (hang[u] == hang[v]) hang[u]++;
  20.     if (hang[u] < hang[v]) swap(u, v);
  21.     root[v] = u;
  22.     return true;
  23.   }
  24. };
  25.  
  26. int main() {
  27.   cin.tie(0)->sync_with_stdio(0);
  28.   int n, m;
  29.   cin >> n >> m;
  30.   vector<array<int,3>> edges(m);
  31.   for (auto &i : edges) {
  32.     cin >> i[1] >> i[2] >> i[0];
  33.   }
  34.   sort(edges.begin(), edges.end(), [](array<int,3> a, array<int,3> b) {
  35.        return a[0] < b[0];
  36.   });
  37.   int ans = 0;
  38.   DSU dsu(n);
  39.   for (auto &i : edges) {
  40.     if (dsu.unite(i[1], i[2])) {
  41.       ans += i[0];
  42.     }
  43.   }
  44.   cout << ans << '\n';
  45. }
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement