Skip to content

Instantly share code, notes, and snippets.

@hemisu
Last active June 6, 2021 12:00
Show Gist options
  • Select an option

  • Save hemisu/80717e90070308595963ac8fcf1817be to your computer and use it in GitHub Desktop.

Select an option

Save hemisu/80717e90070308595963ac8fcf1817be to your computer and use it in GitHub Desktop.
union find
class UF {
constructor(n) {
this.parent = []
this.size = []
this.count = n
while(n--) {
this.parent[n] = n
this.size[n] = 1
}
}
find(i) {
while(this.parent[i] !== i) {
this.parent[i] = this.parent[this.parent[i]] // 路径压缩
i = this.parent[i]
}
return i
}
union(i, j) {
const x = this.find(i)
const y = this.find(j)
if(x === y) return
this.count-- // 联通分量--
if(this.size[x] < this.size[y]) {
// x小树挂到大树y下
this.parent[x] = y
this.size[y] += this.size[x]
} else {
this.parent[y] = x
this.size[x] += this.size[y]
}
}
connect(i, j) {
return this.find(i) === this.find(j)
}
}
// test
const uf = new UF(4)
uf.union(0, 1)
uf.union(2, 3)
console.log('联通分量:', uf.count)
console.log('0, 1:', uf.connect(0, 1))
console.log('1, 2:', uf.connect(1, 2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment