Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <algorithm>
- #include <iostream>
- #include <iomanip>
- #include <utility>
- #include <vector>
- #include <string>
- #include <cmath>
- #include <set>
- #include <map>
- using namespace std;
- typedef long long ll;
- typedef pair <int, int> ii;
- typedef vector <int> vi;
- typedef vector <ii> vii;
- class UnionFind
- {
- private: vi p, rank;
- public:
- vi setSize; int numSets;
- UnionFind (int n)
- {
- rank.assign(n, 0); setSize.assign(n, 1); numSets = n;
- for (int i = 0; i < n; ++i) p.push_back(i);
- }
- int findSet (int i) { return (p[i] == i)? i : p[i] = findSet(p[i]); }
- bool isSameSet (int i, int j) { return findSet(i) == findSet(j); }
- void unionSet (int i, int j)
- {
- if (!isSameSet(i, j))
- {
- --numSets; int x = findSet(i), y = findSet(j);
- if (rank[x] > rank[y])
- {
- p[y] = x; setSize[x] += setSize[y];
- }
- else
- {
- p[x] = y; setSize[y] += setSize[x];
- if (rank[x] == rank[y]) ++rank[y];
- }
- }
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement