Advertisement
Guest User

Dijkstra

a guest
Jul 19th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. typedef long long ll;
  4.  
  5. vector < pair < int, ll > > G[ 100001 ];
  6. ll dist[ 100001 ], ancestor[ 100001 ];
  7. int main(){
  8.  
  9.   int n, m;
  10.   cin >> n >> m;
  11.  
  12.   for(int i = 0; i < m; i ++){
  13.     int a, b, c;
  14.     cin >> a >> b >> c;
  15.     G[ a ].push_back( {b,c} );
  16.     G[ b ].push_back( {a,c} );
  17.   }
  18.  
  19.   for(int i = 0; i <= n; i ++){
  20.     dist[ i ] = 1e18;
  21.   }
  22.  
  23.   dist[ 1 ] = 0;
  24.   priority_queue < pair< ll, int > > Q;
  25.   Q.push({0, 1});
  26.  
  27.   while(!Q.empty()){
  28.     int act_node = Q.top().second;
  29.     ll act_distance = -Q.top().first;
  30.     Q.pop();
  31.  
  32.     for(auto w: G[ act_node ]){
  33.       ll new_dist = act_distance + w.second;
  34.       if(dist[w.first] > new_dist){
  35.         dist[w.first] = new_dist;
  36.         Q.push({-new_dist, w.first});
  37.         ancestor[w.first] = act_node;
  38.       }
  39.     }
  40.   }
  41.  
  42. //  for(int i = 1; i <= n; i ++) cout << i << " -> " << dist[ i ] << endl;
  43.  
  44.   if( dist[ n ] == 1e18 ){
  45.     cout << -1 << endl;
  46.     return 0;
  47.   }
  48.  
  49.   int goal = n;
  50.   vector < int > answer;
  51.   while( goal != 0 ){
  52.     answer.push_back(goal);
  53.     goal = ancestor[ goal ];
  54.   }
  55.   reverse(answer.begin(), answer.end());
  56.   for(auto a: answer){
  57.     cout << a << " ";
  58.   }
  59.  
  60.   return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement