我有一个 DisjointSets 数据结构(从 Cormen 中提取),在 Go 中实现以使用int64.type DisjointSets struct { ranks map[int64]int64 p map[int64]int64}// New returns a new DisjointSetsfunc NewDisjointSets() *DisjointSets { d := DisjointSets{map[int64]int64{}, map[int64]int64{}} return &d}// MakeSet adds element x to the disjoint sets in its own setfunc (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 eachfunc (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 sitsfunc (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等等。我该怎么办呢?到目前为止我尝试过的我已经阅读了有关接口的所有内容,但我似乎不明白如何在不必为每种类型编写完整实现的情况下应用它。
- 3 回答
- 0 关注
- 167 浏览
添加回答
举报
0/150
提交
取消