Skip to content

Commit 0e65792

Browse files
committed
update Union()
1 parent 7df1e38 commit 0e65792

File tree

1 file changed

+16
-19
lines changed

1 file changed

+16
-19
lines changed

dsu.go

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -64,32 +64,29 @@ func (d *DSU) Find(x interface{}) interface{} {
6464
return root.value
6565
}
6666

67-
// Union replaces the set containing x and the set containing y with their union.
68-
// Union uses Find to determine the roots of the trees containing x and y.
69-
// If the roots are the same or one of the elements doesn't exist in the set,
70-
// there is nothing more to do. and Union returns false
71-
// Otherwise, the two sets get be merged. This is done by either setting
72-
// the parent element of the element with the smaller size to the other parent
73-
// and the return of the function in this case is true
67+
// Union replaces the set containing x and the set containing y with their union. It first determines the roots of the sets containing x and y.
68+
// If the roots are the same or one of the elements does not exist in the data structure, there is nothing more to do. Otherwise, the two sets get be merged.
69+
//
70+
// The root of the new set is the root of the set with bigger size. In case both sets have the same size, the root is the root of set y.
71+
//
72+
// It returns true if the merge happened
7473
func (d *DSU) Union(x, y interface{}) bool {
75-
if !d.Contains(x) || !d.Contains(y) {
76-
return false
77-
}
74+
rootx := d.Find(x)
75+
rooty := d.Find(y)
7876

79-
if d.Find(x) == d.Find(y) {
77+
if rootx == nil || rooty == nil || rootx == rooty {
8078
return false
8179
}
8280

83-
nodex := d.nodes[d.Find(x)]
84-
nodey := d.nodes[d.Find(y)]
81+
nodex := d.nodes[rootx]
82+
nodey := d.nodes[rooty]
8583

86-
if nodex.size > nodey.size {
87-
nodey.parent = nodex
88-
nodex.size += nodey.size
89-
} else {
90-
nodex.parent = nodey
91-
nodey.size += nodex.size
84+
if nodex.size <= nodey.size {
85+
nodex, nodey = nodey, nodex
9286
}
9387

88+
nodey.parent = nodex
89+
nodex.size += nodey.size
90+
9491
return true
9592
}

0 commit comments

Comments
 (0)