Dijkstra time complexity with C++ pq
Asked Answered
M

1

1

Dijkstra time complexity is O(V+ElogV) with binary heaps.

But, C++ pq(if used as binary heap), does not support decrease key. One solution suggested is to just insert the same vertex again in pq with decreased distance. For, ex:

From: https://www.hackerearth.com/practice/algorithms/graphs/shortest-path-algorithms/tutorial/

void dijkstra(){
                                                // set the vertices distances as infinity
    memset(vis, false , sizeof vis);            // set all vertex as unvisited
    dist[1] = 0;
    multiset < pair < int , int > > s;          // multiset do the job as a min-priority queue

    s.insert({0 , 1});                          // insert the source node with distance = 0

    while(!s.empty()){

        pair <int , int> p = *s.begin();        // pop the vertex with the minimum distance
        s.erase(s.begin());

        int x = p.s; int wei = p.f;
        if( vis[x] ) continue;                  // check if the popped vertex is visited before
         vis[x] = true;

        for(int i = 0; i < v[x].size(); i++){
            int e = v[x][i].f; int w = v[x][i].s;
            if(dist[x] + w < dist[e]  ){            // check if the next vertex distance could be minimized
                dist[e] = dist[x] + w;
                s.insert({dist[e],  e} );           // insert the next vertex with the updated distance
            }
        }
    }
}

The complexity should increase with this implementation(as opposed to claimed in the article, O(V+ElogV)), as the heap is size>V. I believe the complexity should be O(V+ElogE).

Am I correct? If not, what should be correct complexity?

March answered 29/1, 2021 at 20:3 Comment(0)
M
2

Those bounds are actually equivalent for simple connected graphs. Since

|V| − 1 ≤ |E| ≤ |V| (|V| − 1)/2,

we can take logs and find that

log(|V|) − O(1/|V|) ≤ log(|V| − 1) ≤ log(|E|) ≤ log (|V| (|V| − 1)/2) ≤ 2 log(|V|),

hence Θ(log(|V|)) = Θ(log(|E|)).

Mcallister answered 29/1, 2021 at 20:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.