如何在dijkstra算法的O(log n)时间内更新优先级队列中的密钥?

时间:2012-08-03 19:47:45

标签: algorithm data-structures priority-queue dijkstra

过去一周我一直在研究dijkstra的算法,我在java中有正确的运行代码。它使用数组来计算标准的findMin函数,它给你最小距离的顶点。显然它是O(n)而现在我想用优先级队列(Min Heaps)来实现它

我的想法是:

while (there are unseen Vertex)
{

    vertex= get TheVertex WithSmallest Distance Yet;//(In can be done in O(log n) using heap)

  for this vertex {

    find all of the adjacent edges and traverse them.

    for a particular vertex which is not there in heap yet{

        Simply add it in the queue;
    }
  }
}

但是如果堆中存在特定的顶点,则可以考虑找到的Min节点的距离来更新其距离。

现在我的问题是如何在O(log n)时间内更新堆中的特定元素。

我们无法在O(1)时间内找到该元素吗?

在像我这样天真的实施中,它将是O(n),

那么任何人都可以建议如何处理这个瓶颈?我们如何在O(log n)时间内更新Heap中的特定顶点? (类似地,我们如何在O(1)时间内找到特定元素)

1 个答案:

答案 0 :(得分:4)

我知道这种情况的两种基本方法:

  1. 每当您访问顶点的邻居时,无论它们是否在堆中,都将它们插入堆中。然后,当您获得距离堆最小距离的顶点时,请检查它是否已从堆中删除。如果有,则将其删除并继续。否则,将其标记为已移除并访问所有邻居。

  2. 保持一个显式指针,指向堆中每个元素的位置。然后,您可以对已经找到的元素执行称为“reduce-key”的操作。