Advertisement
minimario

Dijkstra

Jun 22nd, 2015
252
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. #include <utility>
  2. #define pb push_back
  3. #include <iostream>
  4. #include <algorithm>
  5. #include <queue>
  6. #include <vector>
  7.  
  8.  
  9. using namespace std;
  10.  
  11. int main() {
  12.     ios::sync_with_stdio(0);
  13.     cin.tie(0);
  14.     long long dist[100005];
  15.     long long path[100005];
  16.  
  17.     for (long long i=0; i < 100005; i++) {
  18.         dist[i] = 900190019001;
  19.     }
  20.  
  21.     dist[1] = 0;
  22.  
  23.     vector<pair<long long, long long> > g[100005];
  24.  
  25.     long long n, m;
  26.     cin >> n >> m;
  27.     for (long long i=0; i < m; i++) {
  28.         long long a, b, w;
  29.         cin >> a >> b >> w;
  30.         g[a].pb(pair<long long, long long>(b, w));
  31.         g[b].pb(pair<long long, long long>(a, w));
  32.     }
  33.  
  34.     priority_queue< pair<long long, long long>, vector<pair<long long, long long> >, greater<pair<long long, long long> > > pq;
  35.     pq.push(pair<long long, long long>(0, 1));
  36.  
  37.     while (!pq.empty()) {
  38.  
  39.         pair<long long, long long> front = pq.top();
  40.         pq.pop();
  41.         long long d = front.first;
  42.         long long u = front.second;
  43.         if (d > dist[u]) {
  44.             continue;
  45.         }
  46.  
  47.         for (long long j=0; j < g[u].size(); j++) {
  48.             pair<long long, long long> v = g[u][j];
  49.             if (dist[u] + v.second < dist[v.first]) {
  50.                 dist[v.first] = dist[u] + v.second;
  51.                 pq.push(pair<long long, long long>(dist[v.first], v.first));
  52.                 path[v.first] = u;
  53.             }
  54.         }
  55.     }
  56.  
  57.     if (dist[n] == 900190019001) {
  58.         cout << -1 << endl;
  59.         return 0;
  60.     }
  61.  
  62.     vector<long long> x;
  63.     long long i = n;
  64.     while (i != 1) {
  65.         x.pb(i);
  66.         i = path[i];
  67.     }
  68.     x.pb(1);
  69.  
  70.     for (long long i = x.size()-1; i >= 0; i--) {
  71.         cout << x[i] << " ";
  72.     }
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement