Skip to content

Instantly share code, notes, and snippets.

@Chillee
Last active April 30, 2019 09:29
Show Gist options
  • Save Chillee/3f4bc4c936fc62b52661877805c0725b to your computer and use it in GitHub Desktop.
Save Chillee/3f4bc4c936fc62b52661877805c0725b to your computer and use it in GitHub Desktop.
DSU (Disjoint Set Union)
template <int MAXN> struct Dsu {
int par[MAXN], sz[MAXN];
void init(int n) { iota(par, par + n, 0), fill(sz, sz + n, 1); }
int root(int v) { return v == par[v] ? v : (par[v] = root(par[v])); }
void merge(int a, int b) {
if ((a = root(a)) == (b = root(b)))
return;
if (sz[a] < sz[b])
swap(a, b);
par[b] = a;
sz[a] += sz[b];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment