templates/dsu.cpp
compilable
$cat templates/dsu
DSU
Disjoint Set Union with path compression and union by size in near-constant amortized time.
#dsu#union-find#disjoint-set#path-compression
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2e5 + 5;
int par[MAXN], rnk[MAXN];
int numComp;
void init(int n) {
numComp = n;
for (int i = 1; i <= n; i++) { par[i] = i; rnk[i] = 1; }
}
int find(int u) {
return par[u] == u ? u : par[u] = find(par[u]);
}
bool same(int u, int v) { return find(u) == find(v); }
bool unite(int u, int v) {
u = find(u); v = find(v);
if (u == v) return false;
if (rnk[u] < rnk[v]) swap(u, v);
par[v] = u; rnk[u] += rnk[v];
numComp--;
return true;
}
int sz(int u) { return rnk[find(u)]; }
int components() { return numComp; }29 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)
Disjoint Set Union (DSU)
Maintains disjoint sets with near-constant amortized operations.
Operations
find(u) — find the leader of 's set (with path compression)unite(u, v) — merge sets containing and (union by size)same(u, v) — check if and are in the same setsz(u) — size of the set containing components() — number of connected components