Mlxa

ALGO DSU

Dec 20th, 2017
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.17 KB | None | 0 0
  1. #include <iostream>
  2. #include <cassert>
  3. #include <cstdio>
  4. using namespace std;
  5.  
  6. namespace Mlxa {
  7.     #define read cin
  8.     #define eol '\n'
  9.     #define endln cout << eol
  10.     #define print(a) cout << a << ' ';
  11.  
  12.     typedef long long ll;
  13.  
  14.     template <class T> inline void
  15.     println (T t) { cout << t << eol; }
  16.     template <class A, class... B> inline void
  17.     println (A a, B... b) { print(a); println(b...); }
  18.     template <class I> inline void
  19.     printseq (I b, I e) {
  20.         for (I i(b); i != e; ++i)
  21.             print(*i); endln;
  22.     }
  23. } using namespace Mlxa;
  24.  
  25. const ll Size (1000 * 1000);
  26.  
  27. namespace DSU {
  28.     ll n, p[Size], s[Size];
  29.  
  30.     void init (ll N) {
  31.         n = N; for (ll i(0); i < n; ++ i)
  32.             p[i] = i, s[i] = 1;
  33.     }
  34.  
  35.     ll find (ll v) {
  36.         if (p[v] == v) return v;
  37.         return p[v] = find(p[v]);
  38.     }
  39.  
  40.     void unite (ll x, ll y) {
  41.         x = find(x), y = find(y);
  42.         if (s[x] == s[y]) ++ s[y];
  43.         if (s[x] > s[y])  swap(x, y);
  44.         p[x] = y;
  45.     }
  46. }
  47.  
  48. using namespace DSU;
  49. int main () {
  50.     // stdin = freopen("in.txt", "r", stdin);
  51.     ll n; read >> n;
  52.     init(n); char c;
  53.     for (ll x, y; read >> c >> x >> y; ) {
  54.         if (c == 'f') println(find(x));
  55.         if (c == 'u') unite(x, y);
  56.     }
  57.     return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment