Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save 4skinSkywalker/54a5f63dd96d69d79a7b2c1a14a3b991 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.actual = [...this.id]
}
UnionFind.prototype._root = function (id) {
while(id != this.id[id])
id = this.id[id]
return id
}
UnionFind.prototype.union = function (i, k) {
let iroot = this._root(i)
let kroot = this._root(k)
if (iroot === kroot) return
if (this.sz[iroot] > this.sz[kroot]) {
this.id[kroot] = iroot
this.sz[iroot] += this.sz[kroot]
this.actual[iroot] = kroot
} else {
this.id[iroot] = kroot
this.sz[kroot] += this.sz[iroot]
}
}
UnionFind.prototype.delete = function (x) {
this.union(x, x + 1)
}
UnionFind.prototype.after = function (x) {
return this.actual[this._root(x + 1)]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment