首先你不需要使用std::***_heap
函数; STL中已有priority_queue
。
至于更新已经在堆中的值,您可以插入pair
s的索引和距离。并保持距离矢量以验证距离是否仍然有效或已更新;是这样的:
typedef struct {
size_t index; /* index of vertex and the distance at which */
int dist; /* the vertex was pushed to the heap */
} value_t;
/* `a` has less priority than `b` if it is further away */
const auto comp = [](const value_t & a, const value_t & b){
return b.dist < a.dist;
};
priority_queue<value_t, vector<value_t>, decltype(comp)> heap(comp);
/* the *most current* shortest distances for all nodes */
vector<int> dist(n, inf);
然后Dikjstra循环将是这样的:
while(!heap.empty()) {
const auto top = heap.top();
heap.pop();
if(dist[top.index] < top.dist) {
/* the node has already been added at a */
/* shorter distance therefore skip it */
continue;
}
/* process the node & its neighbors */
/* push to the heap neighbors which get their `dist` deccreased */
}
这是真的,有可能是在堆同一节点的多个副本(在不同的距离只有其中一个他们仍然有效);但是您可能会发现堆的大小为O(num. of edges)
,因此堆仍然会执行O(log num. of nodes)
。
实际上这是我正在使用的方法,但是,一个节点可能会被推动很多次的事实使我有点讨厌.... – Alaya