Created
April 13, 2019 11:18
-
-
Save 4skinSkywalker/cc5b8ab899006ba9a7882cf7b64caf66 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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