Advertisement
hearot

Dijkstra (dijkstra)

Jul 9th, 2020
568
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 KB | None | 0 0
  1. /*
  2.  * Public and published.
  3.  * Written by Gabriel Hearot <gabriel@hearot.it>.
  4.  * See https://training.olinfo.it/#/task/dijkstra/statement.
  5.  * https://forum.olinfo.it/t/execution-killed-with-signal-11-su-dijkstra/6236.
  6.  */
  7.  
  8. #include <fstream>
  9. #include <queue>
  10. #include <vector>
  11.  
  12. #define int long long
  13.  
  14. using namespace std;
  15.  
  16. int32_t main() {
  17.   int N, M;
  18.   int src, dest, weight;
  19.   int departure, arrival;
  20.  
  21.   ifstream cin("input.txt");
  22.   ofstream cout("output.txt");
  23.  
  24.   cin >> N >> M;
  25.   cin >> departure >> arrival;
  26.  
  27.   departure--, arrival--;
  28.  
  29.   vector<vector<pair<int, int>>> graph(N);
  30.   vector<int> weights(N, -1);
  31.   priority_queue<int, vector<pair<int, int>>, greater<pair<int, int>>> pq;
  32.  
  33.   while (M--) {
  34.     cin >> src >> dest >> weight;
  35.     graph[src - 1].push_back({dest - 1, weight});
  36.   }
  37.  
  38.   weights[departure] = 0;
  39.   pq.push({0, departure});
  40.  
  41.   while (!pq.empty()) {
  42.     auto current = pq.top();
  43.  
  44.     if (current.second == arrival) {
  45.       cout << current.first << endl;
  46.       return 0;
  47.     }
  48.  
  49.     pq.pop();
  50.  
  51.     for (auto e : graph[current.second]) {
  52.       if (weights[e.first] == -1 ||
  53.           weights[e.first] > e.second + current.first) {
  54.         weights[e.first] = e.second + current.first;
  55.         pq.push({weights[e.first], e.first});
  56.       }
  57.     }
  58.   }
  59.  
  60.   return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement