Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2020
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <stack>
  4. #include "optimization.h"
  5.  
  6. using std::vector;
  7. using std::cin;
  8. using std::cout;
  9. using std::pair;
  10. using std::stack;
  11.  
  12. int main() {
  13.     int n, m, s, f;
  14.     //cin >> n >> m >> s >> f;
  15.     n = readInt();
  16.     m = readInt();
  17.     s = readInt();
  18.     f = readInt();
  19.     s--;
  20.     f--;
  21.     long long mnogo = 10000000000;
  22.     vector<int> par(n, -1);
  23.     vector<long long> dist(n, mnogo);
  24.     vector<bool> used(n, false);
  25.     vector<pair<int, int>> g[n];
  26.  
  27.     dist[s] = 0;
  28.  
  29.     int a, b, w;
  30.     for (int i = 0; i < m; i++){
  31.         //cin >> a >> b >> w;
  32.         a = readInt();
  33.         b = readInt();
  34.         w = readInt();
  35.         g[a - 1].push_back({b - 1, w});
  36.         g[b - 1].push_back({a - 1, w});
  37.     }
  38.  
  39.     for (int i = 0; i < n; i++){
  40.         long long dmin = mnogo;
  41.         int v = 0;
  42.         for (int j = 0; j < n; j++) {
  43.             if (!used[j])
  44.                 if (dist[j] < dmin) {
  45.                     v = j;
  46.                     dmin = dist[j];
  47.                 }
  48.         }
  49.         used[v] = true;
  50.         for (auto &edge : g[v]){
  51.             if (dist[edge.first] > dist[v] + edge.second) {
  52.                 dist[edge.first] = (dist[v] + edge.second);
  53.                 par[edge.first] = v;
  54.             }
  55.         }
  56.     }
  57.  
  58.     if (dist[f] == mnogo){
  59.         //cout << (-1);
  60.         writeInt(-1);
  61.         return 0;
  62.     }
  63.  
  64.     int c = f;
  65.     stack<int> path;
  66.     while (c != s) {
  67.         path.push(c);
  68.         c = par[c];
  69.     }
  70.     writeInt(s + 1, ' ');
  71.     while (!path.empty()) {
  72.         //cout << path.top() << ' ';
  73.         writeInt(path.top() + 1, ' ');
  74.         path.pop();
  75.     }
  76.     //cout << f + 1;
  77.     //writeInt(f + 1);
  78.     return 0;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement