我有一个 DisjointSets 数据结构(从 Cormen 中提取),在 Go 中实现以使用int64
.
type DisjointSets struct {
ranks map[int64]int64
p map[int64]int64
}
// New returns a new DisjointSets
func NewDisjointSets() *DisjointSets {
d := DisjointSets{map[int64]int64{}, map[int64]int64{}}
return &d
}
// MakeSet adds element x to the disjoint sets in its own set
func (d *DisjointSets) MakeSet(x int64) {
d.p[x] = x
d.ranks[x] = 0
}
// Link assigns x to y or vice versa, depending on the rank of each
func (d *DisjointSets) Link(x, y int64) {
if d.ranks[x] > d.ranks[y] {
d.p[y] = x
} else {
d.p[x] = y
if d.ranks[x] == d.ranks[y] {
d.ranks[y] += 1
}
}
}
// FindSet returns the set in which an element x sits
func (d *DisjointSets) FindSet(x int64) int64 {
if x != d.p[x] {
d.p[x] = d.FindSet(d.p[x])
}
return d.p[x]
}
// Union combines two elements x and y into one set.
func (d *DisjointSets) Union(x, y int64) {
d.Link(d.FindSet(x), d.FindSet(y))
}
我想编写尽可能少的增量代码来将此结构用于float64
,string
等。我该怎么做?
到目前为止我尝试过的
我已经阅读了有关接口的所有内容,但我似乎不明白如何在不必为每种类型编写完整实现的情况下应用它。