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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| package max_heap
import "fmt"
type MaxHeap struct { Elements []int Cnt int }
func NewMaxHeap() *MaxHeap { return &MaxHeap {Elements: []int{}, Cnt: -1} }
func GenMaxHeap(elements []int) *MaxHeap { maxHeap := NewMaxHeap() for i:= 0; i < len(elements); i++ { maxHeap.Insert(elements[i]) } return maxHeap }
func (maxHeap MaxHeap) PrintElements() { for i := 0; i <= maxHeap.Cnt; i++ { fmt.Print(maxHeap.Elements[i], " ") } }
func (maxHeap MaxHeap) HeapEmpty() bool { return maxHeap.Cnt == -1 }
func (maxHeap *MaxHeap) Insert(element int) { maxHeap.Cnt += 1 maxHeap.Elements = append(maxHeap.Elements, element) var i = maxHeap.Cnt for i != 0 && maxHeap.Elements[i] > maxHeap.Elements[(i+1) / 2 - 1] { maxHeap.Elements[i], maxHeap.Elements[(i+1) / 2 - 1] = maxHeap.Elements[(i + 1) / 2 - 1], maxHeap.Elements[i] i = (i + 1) / 2 - 1 } }
func (maxHeap *MaxHeap) DeleteMax() int { tmp := maxHeap.Elements[0] maxHeap.Elements[0] = maxHeap.Elements[maxHeap.Cnt] maxHeap.Elements = maxHeap.Elements[0:maxHeap.Cnt] maxHeap.Cnt -= 1 parentIdx := 0 for parentIdx <= maxHeap.Cnt { leftchildIdx := (parentIdx + 1) * 2 - 1 if leftchildIdx > maxHeap.Cnt { break } maxChildIdx := leftchildIdx rightChildIdx := leftchildIdx + 1 if rightChildIdx <= maxHeap.Cnt && maxHeap.Elements[rightChildIdx] > maxHeap.Elements[leftchildIdx] { maxChildIdx = rightChildIdx } if maxHeap.Elements[parentIdx] < maxHeap.Elements[maxChildIdx] { maxHeap.Elements[parentIdx], maxHeap.Elements[maxChildIdx] = maxHeap.Elements[maxChildIdx], maxHeap.Elements[parentIdx]
parentIdx = maxChildIdx } else { break } } return tmp }
func main() { var num int fmt.Scanf("%d", &num) var heapArr []int for i:= 0; i < num; i++ { var tmp int fmt.Scanf("%d", &tmp) heapArr = append(heapArr, tmp) } maxHeap := GenMaxHeap(heapArr) maxHeap.DeleteMax() maxHeap.PrintElements() }
|