voidunion_of(T element1, T element2){ T root1 = find_root(element1); T root2 = find_root(element2);
if (root1 == root2) { // Already in the same set return; }
// Union by rank (attach the tree with lower rank to the one with higher rank) if (ranks[root1] < ranks[root2]) { parents[root1] = root2; } elseif (ranks[root1] > ranks[root2]) { parents[root2] = root1; } else { parents[root2] = root1; ranks[root1]++; } } };
intmain(){ UnionFindSet<int32_t> uf;
for (int32_t i = 1; i <= 10; i++) { uf.add(i); }
auto print = [&]() { std::cout << "-------------------------------" << std::endl; for (int32_t i = 1; i <= 10; i++) { std::cout << "element '" << i << "''s root is: " << uf.find_root(i) << std::endl; } };