- Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy pathUnionFind.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
// 路径压缩 + 秩优化
typeUnionFindstruct {
parent, rank []int
countint
}
// Init define
func (uf*UnionFind) Init(nint) {
uf.count=n
uf.parent=make([]int, n)
uf.rank=make([]int, n)
fori:=rangeuf.parent {
uf.parent[i] =i
}
}
// Find define
func (uf*UnionFind) Find(pint) int {
root:=p
forroot!=uf.parent[root] {
root=uf.parent[root]
}
// compress path
forp!=uf.parent[p] {
tmp:=uf.parent[p]
uf.parent[p] =root
p=tmp
}
returnroot
}
// Union define
func (uf*UnionFind) Union(p, qint) {
proot:=uf.Find(p)
qroot:=uf.Find(q)
ifproot==qroot {
return
}
ifuf.rank[qroot] >uf.rank[proot] {
uf.parent[proot] =qroot
} else {
uf.parent[qroot] =proot
ifuf.rank[proot] ==uf.rank[qroot] {
uf.rank[proot]++
}
}
uf.count--
}
// TotalCount define
func (uf*UnionFind) TotalCount() int {
returnuf.count
}
// UnionFindCount define
// 计算每个集合中元素的个数 + 最大集合元素个数
typeUnionFindCountstruct {
parent, count []int
maxUnionCountint
}
// Init define
func (uf*UnionFindCount) Init(nint) {
uf.parent=make([]int, n)
uf.count=make([]int, n)
fori:=rangeuf.parent {
uf.parent[i] =i
uf.count[i] =1
}
}
// Find define
func (uf*UnionFindCount) Find(pint) int {
root:=p
forroot!=uf.parent[root] {
root=uf.parent[root]
}
returnroot
}
// 不进行秩压缩,时间复杂度爆炸,太高了
// 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, qint) {
proot:=uf.Find(p)
qroot:=uf.Find(q)
ifproot==qroot {
return
}
ifproot==len(uf.parent)-1 {
//proot is root
} elseifqroot==len(uf.parent)-1 {
// qroot is root, always attach to root
proot, qroot=qroot, proot
} elseifuf.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 {
returnuf.count
}
// MaxUnionCount define
func (uf*UnionFindCount) MaxUnionCount() int {
returnuf.maxUnionCount
}
funcmax(aint, bint) int {
ifa>b {
returna
}
returnb
}