【问题标题】:Dijkstra implementation in CPP using priority_queue [closed]使用 priority_queue 在 CPP 中实现 Dijkstra [关闭]
【发布时间】:2014-06-30 04:33:15
【问题描述】:

我正在尝试实现 Dijkstra 的算法,但遇到了一些麻烦。

void Graph::Dijkstra(int source)
{
    // Initialize single source
    [...]

    // Initialize a priority queue with all vertices
    [...]

    // Main loop
    while (!Queue.empty())
    {
        int u = Queue.top();
        Queue.pop();

        // Relax the edges
        [...]
    }
}

在源顶点之后,我的代码总是选择一个距离为无限 (100000) 的顶点,即使还有其他非无限距离的顶点。

虽然由于优先级队列有指向我的顶点的指针,但每次我更改顶点的距离 (v.d) 时它都会更新。

【问题讨论】:

  • 这里有很多关于这个主题的问题和答案(只需查看右侧的相关部分)。请在询问之前进行更彻底的研究!

标签: c++ priority-queue dijkstra


【解决方案1】:

priority_queue 试图在pop 上保持其不变性。您正在放松pop 之后的顶点。进行以下更改:

while (!Queue.empty())
    {
        Vertex *u = Queue.top();

        list<Edge>::iterator i;
        for (i=u->adj.begin(); i!=u->adj.end(); ++i)
        {
            Vertex *v = &vertices[(*i).to];
            Relax(u,v,(*i).w);
        }

        Queue.pop();
    }

【讨论】:

  • 非常感谢,这有效。我不知道为什么我认为队列会始终保持其不变性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-02
  • 2015-02-05
  • 1970-01-01
相关资源
最近更新 更多