Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save 4skinSkywalker/e72d8f47373a9a1aab594b4cccf7c70c 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 = 0
}
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]
} else {
this.id[iroot] = kroot
this.sz[kroot] += this.sz[iroot]
}
this.max = Math.max(this.max, this.sz[iroot], this.sz[kroot])
}
UnionFind.prototype.connected = function (i, k) {
return this._root(i) === this._root(k)
}
UnionFind.prototype.unitary = function () {
return this.max === this.id.length
}
l = console.log
var qu = new UnionFind(5)
qu.union(1,2)
l(qu.unitary()) // false
qu.union(3,4)
l(qu.unitary()) // false
qu.union(1,4)
l(qu.unitary()) // false
qu.union(0,3)
console.log(qu.unitary()) // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment