apl-mhd

dijsktra?Codeforces

Jul 11th, 2017
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | None | 0 0
  1. #include <cstdio>
  2. #include <iostream>
  3. #include <algorithm>
  4. #include <vector>
  5. #include <set>
  6. #include <functional>
  7. #include <queue>
  8. #include <utility>
  9. #include <list>
  10. #include <climits>
  11.  
  12. #define P printf("\n");
  13.  
  14.  
  15. using namespace std;
  16.  
  17. typedef pair<long long, int> PAIR;
  18. const long long INF = LLONG_MAX;
  19.  
  20. int path[1000000] = {0};
  21.  
  22. void printPath(int n) {
  23.  
  24.     if (path[n] == 0)
  25.         return;
  26.  
  27.     else
  28.  
  29.         printPath(path[n]);
  30.  
  31.     cout << " " << n;
  32.  
  33. }
  34.  
  35. int main(int argc, char **argv) {
  36.  
  37.     int n, m, u, v, w;
  38.  
  39.     cin >> n >> m;
  40.  
  41.     if (m == 0)
  42.  
  43.         cout << -1;
  44.  
  45.     else {
  46.  
  47.  
  48.         list <PAIR> x[n + 1];
  49.  
  50.         vector<long long> dist(n + 1, INF);
  51.  
  52.         list<PAIR>::iterator it;
  53.  
  54.         priority_queue <PAIR, vector<PAIR>, greater<PAIR>> q;
  55.  
  56.  
  57.         for (int i = 0; i < m; i++) {
  58.  
  59.             cin >> u >> v >> w;
  60.  
  61.             x[u].push_back(make_pair(w, v));
  62.             x[v].push_back(make_pair(w, u));
  63.  
  64.         }
  65.  
  66.         q.push(make_pair(0, 1));
  67.         dist[1] = 0;
  68.         path[1] = 0;
  69.  
  70.         while (!q.empty()) {
  71.  
  72.             u = q.top().second;
  73.             if(u==n)break;
  74.             q.pop();
  75.  
  76.             for (it = x[u].begin(); it != x[u].end(); it++) {
  77.  
  78.                 w = (*it).first;
  79.                 v = (*it).second;
  80.  
  81.                 if (dist[v] > dist[u] + w) {
  82.  
  83.                     dist[v] = dist[u] + w;
  84.                     q.push(make_pair(dist[v], v));
  85.  
  86.                     path[v] = u;
  87.  
  88.                 }
  89.  
  90.             }
  91.  
  92.         }
  93.  
  94.         if(dist[n]==INF)cout<<"-1\n";
  95.         else {
  96.             cout << "1";
  97.             printPath(n);
  98.         }
  99.  
  100.     }
  101.  
  102. }
Add Comment
Please, Sign In to add comment