Advertisement
Guest User

Untitled

a guest
Sep 18th, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.83 KB | None | 0 0
  1. ll p[N], s[N];
  2.  
  3. ll root(ll x) {
  4.     if (x == p[x]) return x;
  5.     return p[x] = root(p[x]);
  6. }
  7.  
  8. void merge(ll x, ll y) {
  9.     x = root(x), y = root(y);
  10.     if (x != y) {
  11.         if (s[x] > s[y]) swap(x, y);
  12.         p[x] = y;
  13.         s[y] += s[x];
  14.     }
  15. }
  16.  
  17. struct edge {
  18.     ll x, y, dist;
  19.     bool operator< (const edge& other) const {
  20.         return dist < other.dist;
  21.     }
  22. };
  23.  
  24. vector<pll> G[N];
  25. vector<edge> edges;
  26.  
  27. void mst() {
  28.     sort(edges.begin(), edges.end());
  29.     for (int i = 0; i <= n; ++i) p[i] = i, s[i] = 1;
  30.  
  31.     for (auto& e : edges) {
  32.         if (root(e.x) != root(e.y)) {
  33.             merge(e.x, e.y);
  34.             G[e.x].emplace_back(e.y, e.dist);
  35.             G[e.y].emplace_back(e.x, e.dist);
  36.         }
  37.     }
  38. }
  39.  
  40. void clear() {
  41.     for (int i = 0; i < n; ++i) G[i].clear();
  42.     edges.clear();
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement