Skip to content

Commit b968c75

Browse files
committed
Added basic DSU implementation
1 parent 3e27c51 commit b968c75

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

dsu.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package dsu
2+
3+
const noParent = ^uint(0)
4+
5+
type Dsu struct {
6+
parent []uint
7+
size []uint
8+
}
9+
10+
// Create a new Disjoint Set Union data structure with n elements.
11+
// The elements are referred to by their index in the range [0, n).
12+
// The element values are not stored explicitly in the data structure,
13+
// and the user of the data structure is responsible for maintaining
14+
// a correspondence between the element values and their indices.
15+
func NewDsu(n uint) *Dsu {
16+
dsu := &Dsu{
17+
parent: make([]uint, n),
18+
size: make([]uint, n),
19+
}
20+
for i := range dsu.parent {
21+
dsu.parent[i] = noParent
22+
dsu.size[i] = 1
23+
}
24+
return dsu
25+
}
26+
27+
func (d *Dsu) Find(v uint) uint {
28+
if d.parent[v] == noParent {
29+
return v
30+
}
31+
d.parent[v] = d.Find(d.parent[v])
32+
return d.parent[v]
33+
}
34+
35+
func (d *Dsu) Union(v1, v2 uint) {
36+
v1 = d.Find(v1)
37+
v2 = d.Find(v2)
38+
if v1 == v2 {
39+
return
40+
}
41+
if d.size[v1] < d.size[v2] {
42+
v1, v2 = v2, v1
43+
}
44+
d.parent[v2] = v1
45+
d.size[v1] += d.size[v2]
46+
}

0 commit comments

Comments
 (0)