Euler/pkg/datastructures/heap.go

39 lines
688 B
Go

package datastructures
import "container/heap"
type HeapItem struct {
Value any
Priority int
index int
}
type MinHeap []*HeapItem
func (m MinHeap) Len() int { return len(m) }
func (m MinHeap) Less(i, j int) bool { return m[i].Priority < m[j].Priority }
func (m MinHeap) Swap(i, j int) {
m[i], m[j] = m[j], m[i]
m[i].index = i
m[j].index = j
}
func (m *MinHeap) Push(x any) {
*m = append(*m, x.(*HeapItem))
}
func (m *MinHeap) Pop() any {
old := *m
n := len(old)
item := old[n-1]
item.index = 0
old[n-1] = nil
*m = old[0 : n-1]
return item
}
func (m *MinHeap) Update(item *HeapItem, priority int) {
item.Priority = priority
heap.Fix(m, item.index)
}