Skip to content

Instantly share code, notes, and snippets.

@4skinSkywalker
Created April 13, 2019 11:18
Show Gist options
  • Select an option

  • Save 4skinSkywalker/cc5b8ab899006ba9a7882cf7b64caf66 to your computer and use it in GitHub Desktop.

Select an option

Save 4skinSkywalker/cc5b8ab899006ba9a7882cf7b64caf66 to your computer and use it in GitHub Desktop.
function UnionFind(n) {
this.id = [...Array(n)].map((_, i) => i)
this.sz = [...Array(n)].map(_ => 1)
this.max = [...this.id]
}
UnionFind.prototype._root = function (id) {
let max = id
while(id != this.id[id]) {
id = this.id[id]
max = Math.max(max, id)
}
return [id, max]
}
UnionFind.prototype.union = function (i, k) {
let [iroot, imax] = this._root(i)
let [kroot, kmax] = this._root(k)
if (iroot === kroot) return
if (this.sz[iroot] > this.sz[kroot]) {
this.id[kroot] = iroot
this.sz[iroot] += this.sz[kroot]
} else {
this.id[iroot] = kroot
this.sz[kroot] += this.sz[iroot]
}
this.max[iroot] = this.max[kroot] = Math.max(imax, kmax)
}
UnionFind.prototype.findMax = function (i) {
return this.max[this._root(i)[0]]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment