← 中文资源

简体中文版本

优先级变更后修复堆序

给堆元素记录 index,改完优先级调用 heap.Fix 原地修复堆序,取消任务用 heap.Remove 按 index 从中间摘除,不必整体重建。

阅读英文原文

实现说明

真正干活的是函数 Len、Less、Swap、Push,其余都是接线。 本示例的循环部分是 for q.Len() > 0。

使用要点

  • 直接运行文件,输出会带上标签,比如 top:、top after fix:、pop——输出的每一行都能指回产生它的那次调用。
  • 运行整个文件:main 会依次驱动 Push、Len、Pop。

常见问题

运行「优先级变更后修复堆序」会打印什么?

运行文件本身,top:、top after fix:、pop 这些前缀各对应一段演示逻辑。

签名一览:func (q Queue) Len() int

核心语句

func (q Queue) Less(i, j int) bool { return q[i].priority > q[j].priority }
func (q Queue) Len() int           { return len(q) }
func (q Queue) Swap(i, j int) {
	q[i], q[j] = q[j], q[i]
	q[i].index = i
	q[j].index = j
}

代码示例

package main

import (
	"container/heap"
	"fmt"
)

type Task struct {
	name     string
	priority int
	index    int // 堆中位置:heap.Fix / heap.Remove 靠它定位元素
}

type Queue []*Task

func (q Queue) Len() int           { return len(q) }
func (q Queue) Less(i, j int) bool { return q[i].priority > q[j].priority }
func (q Queue) Swap(i, j int) {
	q[i], q[j] = q[j], q[i]
	q[i].index = i
	q[j].index = j
}

func (q *Queue) Push(x any) {
	t := x.(*Task)
	t.index = len(*q)
	*q = append(*q, t)
}

func (q *Queue) Pop() any {
	old := *q
	n := len(old)
	t := old[n-1]
	old[n-1] = nil
	t.index = -1
	*q = old[:n-1]
	return t
}

func main() {
	q := &Queue{}
	heap.Init(q)

	alpha := &Task{name: "alpha", priority: 2}
	beta := &Task{name: "beta", priority: 5}
	heap.Push(q, alpha)
	heap.Push(q, beta)
	heap.Push(q, &Task{name: "gamma", priority: 1})
	fmt.Println("top:", (*q)[0].name)

	// 改了字段就等于改了排序键:原地修复,不必 Pop 再 Push
	alpha.priority = 9
	heap.Fix(q, alpha.index)
	fmt.Println("top after fix:", (*q)[0].name)

	// 取消中间元素:heap.Remove 用它当前的 index 直接摘掉
	heap.Remove(q, beta.index)

	for q.Len() > 0 {
		t := heap.Pop(q).(*Task)
		fmt.Printf("pop %s (priority %d)\n", t.name, t.priority)
	}
}