简体   繁体   English

为什么这个 Dijkstra 算法在不使用最小堆的情况下工作?

[英]Why this Dijkstra algorithm is working without using min heap?

I implemented Dijkstra's algorithm using only a FIFO queue, still it passes all test cases in GFG.我仅使用 FIFO 队列实现了 Dijkstra 算法,但它仍然通过了 GFG 中的所有测试用例。 When will this code fail or if it works then why do we need to use a min heap?这段代码什么时候会失败或者如果它有效,那么为什么我们需要使用最小堆?

vector <int> dijkstra(int V, vector<vector<int>> adj[], int S)
    {
        // adj [] = {{{1, 9}}, {{0, 9}}}

        vector<int> dist(V, INT_MAX);
        queue<pair<int, int>> pq;
        pq.push({0, S});
        while(!pq.empty()) {
            auto f = pq.front();
            pq.pop();
            int node = f.second;
            int d = f.first;
            if (d < dist[node]) 
            {
                dist[node] = d;
                for(auto i: adj[node]) {
                    pq.push({d + i[1], i[0]});
                }
            }
        }
        return dist;
    }

Using a FIFO instead of a min-heap will still give you the correct answer, but the time that your program will take to find that answer will be longer.使用 FIFO 而不是最小堆仍然会给你正确的答案,但是你的程序找到答案的时间会更长。

To be noticeable, you would need to provide a large graph as input.为了引人注目,您需要提供一个大图作为输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM