Advertisement
AlejandroGY

Dijkstra

Apr 27th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. #include <queue>
  2. #include <iostream>
  3.  
  4. using namespace std;
  5. constexpr int INF = 2000000000;
  6. typedef std::pair<int, int> PII;
  7.  
  8. int main( ) {
  9.     int N, s, t;
  10.     std::cin >> N >> s >> t;
  11.     std::vector<std::vector<PII>> edges(N);
  12.     for (int i = 0; i < N; ++i) {
  13.         int M;
  14.         std::cin >> M;
  15.         for (int j = 0; j < M; ++j) {
  16.             int vertex, dist;
  17.             std::cin >> vertex >> dist;
  18.             edges[i].push_back(std::make_pair(dist, vertex));
  19.         }
  20.     }
  21.  
  22.     std::priority_queue<PII, std::vector<PII>, std::greater<PII>> Q;
  23.     std::vector<int> dist(N, INF), dad(N, -1);
  24.  
  25.     Q.push(std::make_pair(0, s));
  26.     dist[s] = 0;
  27.     while (!Q.empty( )) {
  28.         PII p = Q.top( );
  29.         Q.pop( );
  30.  
  31.         int here = p.second;
  32.         if (here == t) break;
  33.         if (dist[here] != p.first) continue;
  34.  
  35.         for (auto it = edges[here].begin( ); it != edges[here].end( ); ++it) {
  36.             if (dist[here] + it->first < dist[it->second]) {
  37.                 dist[it->second] = dist[here] + it->first;
  38.                 dad[it->second] = here;
  39.                 Q.push(std::make_pair(dist[it->second], it->second));
  40.             }
  41.         }
  42.     }
  43.  
  44.     std::cout << dist[t] << "\n";
  45.     if (dist[t] < INF) {
  46.         for (int i = t; i != -1; i = dad[i]) {
  47.             std::cout << i << (i == s ? '\n' : ' ');
  48.         }
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement