Algorithm 围棋中的优先队列

Algorithm 围棋中的优先队列,algorithm,go,priority-queue,Algorithm,Go,Priority Queue,谁能给我解释一下: 我想在GO中实现一个优先级队列(接口实现来自,但优先级最低) 我的代码: pq := make(PriorityQueue, 0) pq.Push(&Item{value: 0, priority: 0}) heap.Init(&pq) fmt.Println(heap.Pop(&pq).(*Item)) item := &Item{value: 1, priority: 10} pq.Push(item) item = &It

谁能给我解释一下: 我想在GO中实现一个优先级队列(接口实现来自,但优先级最低)

我的代码:

pq := make(PriorityQueue, 0)

pq.Push(&Item{value: 0, priority: 0})

heap.Init(&pq)

fmt.Println(heap.Pop(&pq).(*Item))

item := &Item{value: 1, priority: 10}
pq.Push(item)
item = &Item{value: 2, priority: 20}
pq.Push(item)
item = &Item{value: 3, priority: 5}
pq.Push(item)

fmt.Println(heap.Pop(&pq).(*Item))
fmt.Println(heap.Pop(&pq).(*Item))
fmt.Println(heap.Pop(&pq).(*Item))

// Output:
&{0 0 -1}
&{1 10 -1}
&{3 5 -1}
&{2 20 -1}
为什么它不输出:

&{0 0 -1}
&{3 5 -1} 
...

按照这个特定优先级队列的实现方式,您应该在将项目推入队列后调用
heap.Init
,如原始示例所示

pq := make(PriorityQueue, 0)

pq.Push(&Item{value: "0", priority: 0, index: 0})
item := &Item{value: "1", priority: 10, index: 1}
pq.Push(item)
item = &Item{value: "2", priority: 20, index: 2}
pq.Push(item)
item = &Item{value: "3", priority: 5, index: 3}
pq.Push(item)

heap.Init(&pq)

fmt.Println(heap.Pop(&pq).(*Item))
fmt.Println(heap.Pop(&pq).(*Item))
fmt.Println(heap.Pop(&pq).(*Item))
fmt.Println(heap.Pop(&pq).(*Item))

将按预期的优先级顺序打印项目。

首先请注意,您说过您希望优先级最低,但数字越高,优先级越高。所以应该是20,10,5,0

在文件中:

取出物品;它们以递减的优先顺序到达

我只是把你的数据放在doc页面的示例中(你提供的链接)。 请查看:

主要区别在于
heap.Init(&pq)
位置


编辑:@在我键入我的答案时提供了答案。

TLDR使用
heap.Push(…)
heap.Pop(…)
来添加和删除队列,并保留顺序

问题出在您的设置中。您不应该直接从队列中推送或弹出,并期望它被订购。调用
heap.Init(&pq)
将对整个堆进行排序,因此您可以一次装入所有内容并对所有内容进行排序

对于您的用例,您应该将堆实用程序用于push和pop。添加到队列时,请使用
heap.Push(…)
而不是
pq.Push(…)


后续推送和POP将始终以这种方式订购。因为每个项目都是在插入时排序的,所以不需要调用
heap.Init(&pq)
。这更接近于在推送和pop分散的生产环境中使用的实现。

谢谢您的回答,但我需要在推送新项之前弹出一些项(类似这样的smth):heap.Init(&pq)for{heap.pop(&pq)。(*项)…pq.Push(项)}Hi Jus,我看你还没有接受答案。你能澄清一下你需要什么,以便我们能更好地详细说明答案吗?
pq := make(PriorityQueue, 0)

heap.Push(&pq, &Item{value: "0", priority: 0, index: 0})
item := &Item{value: "1", priority: 10, index: 1}
heap.Push(&pq, item)
item = &Item{value: "2", priority: 20, index: 2}
heap.Push(&pq, item)
item = &Item{value: "3", priority: 5, index: 3}
heap.Push(&pq, item)

fmt.Println(heap.Pop(&pq).(*Item))
fmt.Println(heap.Pop(&pq).(*Item))
fmt.Println(heap.Pop(&pq).(*Item))
fmt.Println(heap.Pop(&pq).(*Item))