Performance of Dijkstra's algorithm implementation

前端 未结 2 1682
北海茫月
北海茫月 2020-12-18 05:07

Below is an implementation of Dijkstra\'s algorithm I wrote from the pseudocode in the Wikipedia article. For a graph with about 40 000 nodes and 80 000 edges, it takes 3 o

相关标签:
2条回答
  • 2020-12-18 06:05

    There are several things you can improve on this:

    • implementing the priority queue with sort and erase adds a factor of |E| to the runtime - use the heap functions of the STL to get a log(N) insertion and removal into the queue.
    • do not put all the nodes in the queue at once but only those where you have discovered a path (which may or may not be the optimal, as you can find an indirect path through nodes in the queue).
    • creating objects for every node creates unneccessary memory fragmentation. If you care about squeezing out the last 5-10%, you could think about a solution to represent the incidence matrix and other information directly as arrays.
    0 讨论(0)
  • 2020-12-18 06:09

    Use priority_queue.

    My Dijkstra implementation:

    struct edge
    {
        int v,w;
        edge(int _w,int _v):w(_w),v(_v){}
    };
    vector<vector<edge> > g;
    enum color {white,gray,black};
    vector<int> dijkstra(int s)
    {
        int n=g.size();
        vector<int> d(n,-1);
        vector<color> c(n,white);
        d[s]=0;
        c[s]=gray;
        priority_queue<pair<int,int>,vector<pair<int,int> >,greater<pair<int,int> > > q; // declare priority_queue
        q.push(make_pair(d[s],s)); //push starting vertex
        while(!q.empty())
        {
            int u=q.top().second;q.pop(); //pop vertex from queue
            if(c[u]==black)continue;
            c[u]=black; 
            for(int i=0;i<g[u].size();i++)
            {
                int v=g[u][i].v,w=g[u][i].w;
                if(c[v]==white) //new vertex found
                {
                    d[v]=d[u]+w;
                    c[v]=gray;
                    q.push(make_pair(d[v],v)); //add vertex to queue
                }
                else if(c[v]==gray && d[v]>d[u]+w) //shorter path to gray vertex found
                {
                    d[v]=d[u]+w;
                    q.push(make_pair(d[v],v)); //push this vertex to queue
                }
            }
        }
        return d;
    }
    
    0 讨论(0)
提交回复
热议问题