-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpathcompressionunionfund.go
47 lines (42 loc) · 1.01 KB
/
pathcompressionunionfund.go
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
package disjointset
type PathCompressionUnionFind struct {
roots []int
ranks []int
}
func NewPathCompressionUnionFind(qty int) *PathCompressionUnionFind {
roots := make([]int, qty)
ranks := make([]int, qty)
for i, _ := range roots {
roots[i] = i
ranks[i] = 0
}
return &PathCompressionUnionFind{
roots: roots,
ranks: ranks,
}
}
func (pcuf *PathCompressionUnionFind) Find(index int) int {
if pcuf.roots[index] == index {
return index
}
pcuf.roots[index] = pcuf.Find(pcuf.roots[index])
return pcuf.roots[index]
}
func (pcuf *PathCompressionUnionFind) Union(f int, s int) {
froot := pcuf.Find(f)
sroot := pcuf.Find(s)
if sroot != froot {
pcuf.roots[sroot] = froot
}
if pcuf.ranks[sroot] < pcuf.ranks[froot] {
pcuf.roots[sroot] = froot
} else if pcuf.ranks[sroot] > pcuf.ranks[froot] {
pcuf.roots[froot] = sroot
} else if pcuf.ranks[sroot] == pcuf.ranks[froot] {
pcuf.roots[sroot] = froot
pcuf.ranks[froot]++
}
}
func (pcuf *PathCompressionUnionFind) GetRoots() []int {
return pcuf.roots
}