Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d3bc759

Browse files
Create connecting-cities-with-minimum-cost.go
1 parent 40acd53 commit d3bc759

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
//https://leetcode.com/problems/connecting-cities-with-minimum-cost/
2+
3+
package connecting_cities_with_minimum_cost
4+
5+
import "sort"
6+
7+
func minimumCost(n int, connections [][]int) int {
8+
if n == 1 {
9+
return 0
10+
}
11+
sort.Slice(connections, func(i, j int) bool {
12+
return connections[i][2] < connections[j][2]
13+
})
14+
ds := NewDisjointSet(n)
15+
total := 0
16+
for _, c := range connections {
17+
if ds.Find(c[0]) != ds.Find(c[1]) {
18+
ds.Union(c[0], c[1])
19+
total += c[2]
20+
n--
21+
}
22+
}
23+
if n > 1 {
24+
return -1
25+
}
26+
return total
27+
}
28+
29+
type DisjointSet struct {
30+
parent []int
31+
rank []int
32+
}
33+
34+
func NewDisjointSet(n int) *DisjointSet {
35+
parent := make([]int, n+1)
36+
rank := make([]int, n+1)
37+
for i := 1; i <= n; i++ {
38+
parent[i] = i
39+
rank[i] = 1
40+
}
41+
return &DisjointSet{parent, rank}
42+
}
43+
44+
func (d *DisjointSet) Find(x int) int {
45+
for d.parent[x] != x {
46+
d.parent[x] = d.parent[d.parent[x]]
47+
x = d.parent[x]
48+
}
49+
return x
50+
}
51+
52+
func (d *DisjointSet) Union(x, y int) {
53+
xRoot := d.Find(x)
54+
yRoot := d.Find(y)
55+
if xRoot == yRoot {
56+
return
57+
}
58+
if d.rank[xRoot] < d.rank[yRoot] {
59+
d.parent[xRoot] = yRoot
60+
} else if d.rank[xRoot] > d.rank[yRoot] {
61+
d.parent[yRoot] = xRoot
62+
} else {
63+
d.parent[yRoot] = xRoot
64+
d.rank[xRoot]++
65+
}
66+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /