Implement a DSU (Union-Find)
core
Implement the disjoint-set union structure you'd reach for in any connectivity problem: find must follow parents to the root (path compression recommended), unite links the two roots.
Operations arrive as U a b (unite) and F a b (are a and b connected?). Your find must return the same root for connected nodes even across chains like U 0 1, U 1 2.
Example: starting from DSU dsu(3), calling dsu.unite(0, 1) then dsu.unite(1, 2) links all three nodes through a chain; dsu.find(0) == dsu.find(2) afterward even though 0 and 2 were never united directly.
Input format: each test in tests/*.in is laid out as:
- Line 1:
n q, the element count and the number of operations; elements are numbered0ton - 1. - Next
qlines: one operation each, eitherU a b(union the sets holdingaandb) orF a b(print whetheraandbare in the same set).
Test 02.in reads:
4 4
U 0 1
U 1 2
F 0 2
F 0 3
This is 4 elements and 4 operations: two unions chain 0, 1, 2 together, then F 0 2 prints 1 and F 0 3 prints 0.
Where you'll use it:
✦ Solution & editorial unlock with the pass.