go 数据结构 – 优先队列(堆)

使用“container/heap”包,构建堆或者优先队列,需要自己定义Sort方法的内容及Push Pop方法。

//官方示例1 最小堆
// This example demonstrates an integer heap built using the heap interface.
package main

import (
	"container/heap"
	"fmt"
)

// An IntHeap is a min-heap of ints.
type IntHeap []int

func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *IntHeap) Push(x interface{}) {
	// Push and Pop use pointer receivers because they modify the slice's length,
	// not just its contents.
	*h = append(*h, x.(int))
}

func (h *IntHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

// This example inserts several ints into an IntHeap, checks the minimum,
// and removes them in order of priority.
func main() {
	h := &IntHeap{2, 1, 5}
	heap.Init(h)
	heap.Push(h, 3)
	fmt.Printf("minimum: %d\n", (*h)[0])
	for h.Len() > 0 {
		fmt.Printf("%d ", heap.Pop(h))
	}
}

//官方示例2 优先队列
// This example demonstrates a priority queue built using the heap interface.
package main

import (
	"container/heap"
	"fmt"
)

// An Item is something we manage in a priority queue.
type Item struct {
	value    string // The value of the item; arbitrary.
	priority int    // The priority of the item in the queue.
	// The index is needed by update and is maintained by the heap.Interface methods.
	index int // The index of the item in the heap.
}

// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Item

func (pq PriorityQueue) Len() int { return len(pq) }

func (pq PriorityQueue) Less(i, j int) bool {
	// We want Pop to give us the highest, not lowest, priority so we use greater than here.
	return pq[i].priority > pq[j].priority
}

func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *PriorityQueue) Push(x interface{}) {
	n := len(*pq)
	item := x.(*Item)
	item.index = n
	*pq = append(*pq, item)
}

func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	old[n-1] = nil  // avoid memory leak
	item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}

// update modifies the priority and value of an Item in the queue.
func (pq *PriorityQueue) update(item *Item, value string, priority int) {
	item.value = value
	item.priority = priority
	heap.Fix(pq, item.index)
}

// This example creates a PriorityQueue with some items, adds and manipulates an item,
// and then removes the items in priority order.
func main() {
	// Some items and their priorities.
	items := map[string]int{
		"banana": 3, "apple": 2, "pear": 4,
	}

	// Create a priority queue, put the items in it, and
	// establish the priority queue (heap) invariants.
	pq := make(PriorityQueue, len(items))
	i := 0
	for value, priority := range items {
		pq[i] = &Item{
			value:    value,
			priority: priority,
			index:    i,
		}
		i++
	}
	heap.Init(&pq)

	// Insert a new item and then modify its priority.
	item := &Item{
		value:    "orange",
		priority: 1,
	}
	heap.Push(&pq, item)
	pq.update(item, item.value, 5)

	// Take the items out; they arrive in decreasing priority order.
	for pq.Len() > 0 {
		item := heap.Pop(&pq).(*Item)
		fmt.Printf("%.2d:%s ", item.priority, item.value)
	}
}


//实际使用
import (
    "container/heap"
    "fmt"
)

type Item struct {
    day int
    apple int
}

type PriortyQueue []*Item

func (pq PriortyQueue) Len() int {return len(pq)}
func (pq PriortyQueue) Less(i, j int) bool {
    return pq[i].day > pq[j].day
}
func (pq PriortyQueue) Swap(i, j int) {
    pq[i], pq[j] = pq[j], pq[i]
}

func (pq *PriortyQueue) Push(x interface{}) {
    item := x.(*Item)
    *pq = append(*pq, item)
}

func (pq *PriortyQueue) Pop() interface{} {
    old := *pq
    n := len(old)
    item := old[n-1]
    old[n-1] = nil
    *pq = old[0:n-1]
    return item
}

func eatenApples(apples []int, days []int) int {
    pq := make(PriortyQueue, 0)
    n := len(apples)
    res := 0
    for i := 0; i <= 40000; i++ {

        if i < n && apples[i] > 0 {
            heap.Push(&pq, &Item{day: i+days[i]-1, apple: apples[i]})
        }
        for pq.Len() > 0 && pq[pq.Len()-1].day < i {
            _ = pq.Pop()    
        }
        if pq.Len() == 0 {continue}
        x := pq.Pop().(*Item)
        x.apple -= 1
        res += 1
        if x.apple > 0 {heap.Push(&pq, x)}
    }
    return res
}
//附Scala中优先队列使用
import scala.collection.mutable.PriorityQueue
object Solution {
    def eatenApples(apples: Array[Int], days: Array[Int]): Int = {
        val heap = PriorityQueue.empty[(Int, Int)](Ordering.by(n => n._1)).reverse
        var res = 0
        var n = apples.length
        var i = 0

        while (i < n || heap.length > 0){
        //while (i < 10){
            if (i < n && apples(i) > 0) {
                heap.enqueue(((i + days(i) -1), apples(i)))
            }
            while (heap.length > 0 && heap.head._1 < i) {
                var  temp = heap.dequeue
            }
            if (heap.length > 0) {
                var x = heap.dequeue
                res += 1
                if (x._2-1 > 0) {
                    heap.enqueue((x._1, x._2-1))
                }
            }
            i += 1 
        }
        return res
    }
}