1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
import "container/heap"
func maxSpanningTree(edges [][]int, n int) [][]int {
graph := make([][][2]int, n)
for _, edge := range edges {
u, v, w := edge[0], edge[1], edge[2]
graph[u] = append(graph[u], [2]int{v, w})
graph[v] = append(graph[v], [2]int{u, w})
}
visited := make([]bool, n)
pq := &MaxHeap{}
heap.Init(pq)
var ans [][]int
visited[0] = true
for _, neighbor := range graph[0] {
heap.Push(pq, []int{neighbor[1], 0, neighbor[0]})
}
for pq.Len() > 0 && len(ans) < n-1 {
curr := heap.Pop(pq).([]int)
weight, u, v := curr[0], curr[1], curr[2]
if visited[v] {
continue
}
visited[v] = true
ans = append(ans, []int{u, v, weight})
for _, neighbor := range graph[v] {
if !visited[neighbor[0]] {
heap.Push(pq, []int{neighbor[1], v, neighbor[0]})
}
}
}
return ans
}
type MaxHeap [][]int
func (h MaxHeap) Len() int { return len(h) }
func (h MaxHeap) Less(i, j int) bool { return h[i][0] > h[j][0] }
func (h MaxHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *MaxHeap) Push(x interface{}) {
*h = append(*h, x.([]int))
}
func (h *MaxHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
|