Skip to content

Instantly share code, notes, and snippets.

@toantd90
Created March 30, 2023 21:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toantd90/97f6f71cf24783578be5e574a4ca5518 to your computer and use it in GitHub Desktop.
Save toantd90/97f6f71cf24783578be5e574a4ca5518 to your computer and use it in GitHub Desktop.
class DSU {
constructor(n) {
this.ranks = [];
this.parent = [];
for (let i = 0; i < n; i++) {
this.ranks[i] = 0;
this.parent[i] = i;
}
this.group = n;
}
findSet(u) {
if (this.parent[u] != u) {
this.parent[u] = this.findSet(this.parent[u]);
}
return this.parent[u];
}
unionSet(u, v) {
const up = this.findSet(u);
const vp = this.findSet(v);
if (up == vp) {
return;
}
this.group--;
if (this.ranks[vp] > this.ranks[up]) {
this.parent[up] = vp;
} else if (this.ranks[up] > this.ranks[vp]) {
this.parent[vp] = up;
} else {
this.parent[vp] = up;
this.ranks[up]++;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment