1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| class UnionFind { public: UnionFind(int n) { f.assign(n + 1, 0); rank.assign(n + 1, 1);
for(int i = 0; i <= n; i++) { f[i] = i; } }
int find(int x) { return x == f[x] ? x : (f[x] = find(f[x])); }
void merge(int a, int b) { int x = find(a), y = find(b); if(rank[x] <= rank[y]) { f[x] = y; } else { f[y] = x; } if(rank[x] == rank[y] && x != y) { rank[y]++; } }
bool connected(int a, int b) { int roota = find(a), rootb = find(b); return roota == rootb; }
private: vector<int> f, rank; };
|