File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments