$cat templates/dsu

Disjoint Set Union (DSU)

Union-Find data structure with path compression and union by size

O(α(n))Data Structures
Jun 21, 2026
#dsu#union-find#graph
$cat code/
cpp
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
class DSU {
  vector<int> parent, sz;
public:
  DSU(int n) {
    parent.resize(n);
    sz.resize(n, 1);
    for (int i = 0; i < n; i++) parent[i] = i;
  }
  int find(int x) {
    return parent[x] == x ? x : parent[x] = find(parent[x]);
  }
  void unite(int a, int b) {
    a = find(a), b = find(b);
    if (a == b) return;
    if (sz[a] < sz[b]) swap(a, b);
    parent[b] = a;
    sz[a] += sz[b];
  }
  bool same(int a, int b) { return find(a) == find(b); }
  int size(int x) { return sz[find(x)]; }
};
21 linesutf-8
$cat notes.txt

Also known as Union-Find. Use for connected components, Kruskal's MST, dynamic connectivity.