-
-
Notifications
You must be signed in to change notification settings - Fork 5.7k
/
UnionFind.go
134 lines (120 loc) · 2.46 KB
/
UnionFind.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package template
// UnionFind defind
// 路径压缩 + 秩优化
type UnionFind struct {
parent, rank []int
count int
}
// Init define
func (uf *UnionFind) Init(n int) {
uf.count = n
uf.parent = make([]int, n)
uf.rank = make([]int, n)
for i := range uf.parent {
uf.parent[i] = i
}
}
// Find define
func (uf *UnionFind) Find(p int) int {
root := p
for root != uf.parent[root] {
root = uf.parent[root]
}
// compress path
for p != uf.parent[p] {
tmp := uf.parent[p]
uf.parent[p] = root
p = tmp
}
return root
}
// Union define
func (uf *UnionFind) Union(p, q int) {
proot := uf.Find(p)
qroot := uf.Find(q)
if proot == qroot {
return
}
if uf.rank[qroot] > uf.rank[proot] {
uf.parent[proot] = qroot
} else {
uf.parent[qroot] = proot
if uf.rank[proot] == uf.rank[qroot] {
uf.rank[proot]++
}
}
uf.count--
}
// TotalCount define
func (uf *UnionFind) TotalCount() int {
return uf.count
}
// UnionFindCount define
// 计算每个集合中元素的个数 + 最大集合元素个数
type UnionFindCount struct {
parent, count []int
maxUnionCount int
}
// Init define
func (uf *UnionFindCount) Init(n int) {
uf.parent = make([]int, n)
uf.count = make([]int, n)
for i := range uf.parent {
uf.parent[i] = i
uf.count[i] = 1
}
}
// Find define
func (uf *UnionFindCount) Find(p int) int {
root := p
for root != uf.parent[root] {
root = uf.parent[root]
}
return root
}
// 不进行秩压缩,时间复杂度爆炸,太高了
// func (uf *UnionFindCount) union(p, q int) {
// proot := uf.find(p)
// qroot := uf.find(q)
// if proot == qroot {
// return
// }
// if proot != qroot {
// uf.parent[proot] = qroot
// uf.count[qroot] += uf.count[proot]
// }
// }
// Union define
func (uf *UnionFindCount) Union(p, q int) {
proot := uf.Find(p)
qroot := uf.Find(q)
if proot == qroot {
return
}
if proot == len(uf.parent)-1 {
//proot is root
} else if qroot == len(uf.parent)-1 {
// qroot is root, always attach to root
proot, qroot = qroot, proot
} else if uf.count[qroot] > uf.count[proot] {
proot, qroot = qroot, proot
}
//set relation[0] as parent
uf.maxUnionCount = max(uf.maxUnionCount, (uf.count[proot] + uf.count[qroot]))
uf.parent[qroot] = proot
uf.count[proot] += uf.count[qroot]
}
// Count define
func (uf *UnionFindCount) Count() []int {
return uf.count
}
// MaxUnionCount define
func (uf *UnionFindCount) MaxUnionCount() int {
return uf.maxUnionCount
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}