Created
March 30, 2023 21:57
-
-
Save toantd90/97f6f71cf24783578be5e574a4ca5518 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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