FastDijkstra.cc 883 B

12345678910111213141516171819202122232425
  1. // Implementation of Dijkstra's algorithm using adjacency lists
  2. // and priority queue for efficiency.
  3. // Running time: O(|E| log |V|)
  4. // USAGE: edges: pair of weight/destination, source, target
  5. void Dijkstra(VVPII edges, int s, int t) {
  6. // use priority queue in which top element has the "smallest" priority
  7. priority_queue<PII, VPII, greater<PII> > Q;
  8. VI dist(edges.size(), INF), dad(edges.size(), -1);
  9. Q.push(make_pair (0, s));
  10. dist[s] = 0;
  11. while(!Q.empty()){
  12. PII p = Q.top();
  13. if (p.second == t) break;
  14. Q.pop();
  15. int here = p.second;
  16. for(VPII::iterator it=edges[here].begin(); it!=edges[here].end(); it++){
  17. if(dist[here] + it->first < dist[it->second]){
  18. dist[it->second] = dist[here] + it->first;
  19. dad[it->second] = here;
  20. Q.push (make_pair (dist[it->second], it->second));
  21. }
  22. }
  23. }
  24. // dist contains distances
  25. }