Disjoint set union
Tracks the connected components of a graph as edges are added. Initially, each vertex is in its own component. You can join two vertices or check whether they are connected.
Implementation
struct DSU {
vector<int> P, S;
DSU(int N) : P(N, -1), S(N, 1) {}
int leader(int v) {
if (P[v] == -1) return v;
return P[v] = leader(P[v]);
}
void join(int v, int u) {
v = leader(v);
u = leader(u);
if (v == u) return;
if (S[u] > S[v]) swap(v, u);
P[u] = v;
S[v] += S[u];
}
};
Interface
| Operation | Description | Constraints | Time |
|---|---|---|---|
DSU(N) |
Creates a graph with vertices and no edges. | ||
leader(v) |
Returns a representative of v’s component. Two vertices are connected if they have the same leader. |
amortized | |
join(v, u) |
Adds an edge between v and u. |
amortized |
Here, is the inverse Ackermann function. Both operations take nearly constant time in practice.