In The Dijkstra's algo we need to extract the minimum of D where D is the distance from node 0. But as D gets updated with the distance randomly how could we extract the minimum. Eg: Let at an instance we have the below array and we have used the node 0(its distance to itself is always 0) and accordingly its adjacent node2 and node5 get updated with distance from node 0. D: 0 INF 3 INF INF 1 INF If we use O(n) then ultimately we are using O(n^2) as we will be updating the adjacent of node 5 and again extracting the minimum by using O(n). Is there a better approach to extract the minimum?? asked 28 Jun '15, 14:00

You can refer here http://zobayer.blogspot.de/2009/12/dijkstrasalgorithminc.html answered 29 Jun '15, 18:52

Yes..use heap to store these. Priority queue is the key. answered 28 Jun '15, 14:26

Answer is hidden as author is suspended. Click here to view.
answered 19 Nov '16, 22:47

Answer is hidden as author is suspended. Click here to view.
answered 19 Nov '16, 22:49

I think function can be helpful. Only integer 1 in case of no path. void dijkstra(int start, vector<pii>G[]) { long long int dist[1000],prev[1000]; priority_queue<pii,vector<pii>,greater<pii> >q; vector<int>path; for(int i=1; i<=n; i++) { dist[i]=infinity; prev[i]=1; } q.push(pii(0,start)); dist[start]=0; while(!q.empty()) { u=q.top().second; q.pop(); for(int i=0; i<G[u].size();i++) { v=G[u][i].second; w=G[u][i].first; if(dist[u]+w<dist[v]) { dist[v]=dist[u]+w; prev[v]=u; q.push(pii(dist[v],v)); } } } if(prev[n]==1) { cout<<"1"<<endl; } else { u=n; while(u!=1) { path.push_back((u)); u=prev[u]; } for(int i=path.size()1; i>=0; i) { cout<<path[i]<<" "; } cout<<endl; } } Reference : Blog answered 19 Nov '16, 14:17

The trick here is to use a priority queue , where each and every distance would be pushed. Next we will eject elements one by one , note that if the distance is already ejected and copied in the minimum distance vector , it will be ejected but not copied into the min distance vector , here is an implementation of it , I made for Free Tickets (INOI 2012) problem,
Hope it helps , cheers! answered 19 Nov '16, 14:37
