Performance of Dijkstra's algorithm implementation

前端 未结 2 1697
北海茫月
北海茫月 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:09

    Use priority_queue.

    My Dijkstra implementation:

    struct edge
    {
        int v,w;
        edge(int _w,int _v):w(_w),v(_v){}
    };
    vector > g;
    enum color {white,gray,black};
    vector dijkstra(int s)
    {
        int n=g.size();
        vector d(n,-1);
        vector c(n,white);
        d[s]=0;
        c[s]=gray;
        priority_queue,vector >,greater > > 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;id[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;
    }
    

提交回复
热议问题