FastDijkstra.cc 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Implementation of Dijkstra's algorithm using adjacency lists
  2. // and priority queue for efficiency.
  3. //
  4. // Running time: O(|E| log |V|)
  5. #include <queue>
  6. #include <stdio.h>
  7. using namespace std;
  8. const int INF = 2000000000;
  9. typedef pair<int,int> PII;
  10. int main(){
  11. int N, s, t;
  12. scanf ("%d%d%d", &N, &s, &t);
  13. vector<vector<PII> > edges(N);
  14. for (int i = 0; i < N; i++){
  15. int M;
  16. scanf ("%d", &M);
  17. for (int j = 0; j < M; j++){
  18. int vertex, dist;
  19. scanf ("%d%d", &vertex, &dist);
  20. edges[i].push_back (make_pair (dist, vertex)); // note order of arguments here
  21. }
  22. }
  23. // use priority queue in which top element has the "smallest" priority
  24. priority_queue<PII, vector<PII>, greater<PII> > Q;
  25. vector<int> dist(N, INF), dad(N, -1);
  26. Q.push (make_pair (0, s));
  27. dist[s] = 0;
  28. while (!Q.empty()){
  29. PII p = Q.top();
  30. if (p.second == t) break;
  31. Q.pop();
  32. int here = p.second;
  33. for (vector<PII>::iterator it=edges[here].begin(); it!=edges[here].end(); it++){
  34. if (dist[here] + it->first < dist[it->second]){
  35. dist[it->second] = dist[here] + it->first;
  36. dad[it->second] = here;
  37. Q.push (make_pair (dist[it->second], it->second));
  38. }
  39. }
  40. }
  41. printf ("%d\n", dist[t]);
  42. if (dist[t] < INF)
  43. for(int i=t;i!=-1;i=dad[i])
  44. printf ("%d%c", i, (i==s?'\n':' '));
  45. return 0;
  46. }