Created
April 13, 2019 11:57
-
-
Save 4skinSkywalker/54a5f63dd96d69d79a7b2c1a14a3b991 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.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