-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathweight-quick-union.ts
More file actions
50 lines (43 loc) · 946 Bytes
/
weight-quick-union.ts
File metadata and controls
50 lines (43 loc) · 946 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* 并查集
* 加权 quick-union 算法
*/
export default class WeightQuickUnionUF {
private _count: number
private id: number[]
private sz: number[]
constructor(N: number) {
this._count = N
this.id = []
this.sz = []
for (let i = 0; i < N; i++) {
this.id[i] = i
this.sz[i] = 1
}
}
count(): number {
return this._count
}
connected(p: number, q: number): boolean {
return this.find(p) === this.find(q)
}
find(p: number): number {
// 跟随链接找到根节点
while (p !== this.id[p]) p = this.id[p]
return p
}
union(p: number, q: number) {
const i = this.find(p)
const j = this.find(q)
if (i === j) return
// 将小树的根节点连接到大树的根节点
if (this.sz[i] < this.sz[j]) {
this.id[i] = j
this.sz[j] += this.sz[i]
} else {
this.id[j] = i
this.sz[i] += this.sz[j]
}
this._count--
}
}