fenwick tree

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 NN vertices and no edges. N≥0{N \ge 0} O(N){O(N)}
leader(v) Returns a representative of v’s component. Two vertices are connected if they have the same leader. 0≤v<N{0 \le v < N} O(α(N)){O(\alpha(N))} amortized
join(v, u) Adds an edge between v and u. 0≤v,u<N{0 \le v, u < N} O(α(N)){O(\alpha(N))} amortized

Here, α\alpha is the inverse Ackermann function. Both operations take nearly constant time in practice.