Advertisement
informaticage

Dijsktra

Jul 1st, 2023
1,036
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.18 KB | None | 0 0
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <queue>
  4. #include <utility>
  5. #include <vector>
  6. #include <cstdint>
  7.  
  8. using namespace std;
  9.  
  10. #define DISTANCE_INITIALIZATION_VALUE -1
  11.  
  12. void add_edge_directed(
  13.     vector<vector<pair<std::int64_t, std::int64_t>>> &G,
  14.     std::int64_t u,
  15.     std::int64_t v,
  16.     std::int64_t weight
  17. ) {
  18.     G.at(u).push_back(make_pair(v, weight));
  19.     // G.at(v).push_back(make_pair(u, weight));
  20. }
  21.  
  22. class Compare {
  23.    public:
  24.     // Ringraziamo l'umile dipendente cicciottello
  25.     // per aver scoperto la necessitá di una inspiegabile parentesi tonda
  26.     bool operator() (
  27.       pair<std::int64_t, std::int64_t> &lhs,
  28.       pair<std::int64_t, std::int64_t> &rhs
  29.     ) {
  30.         return lhs.second > rhs.second;
  31.     }
  32. };
  33.  
  34. int main() {
  35.     freopen("input.txt", "r", stdin);
  36.     freopen("output.txt", "w", stdout);
  37.  
  38.     std::int64_t V, E;
  39.     cin >> V >> E;
  40.     vector<vector<pair<std::int64_t, std::int64_t>>> G(
  41.         V,
  42.         vector<pair<std::int64_t, std::int64_t>>()
  43.     );
  44.  
  45.     std::int64_t source, destination;
  46.     cin >> source >> destination;
  47.     source--;
  48.     destination--;
  49.  
  50.     for (std::int64_t edge = 0; edge < E; edge++) {
  51.         std::int64_t u, v, w;
  52.         cin >> u >> v >> w;
  53.         u--;
  54.         v--;
  55.         add_edge_directed(G, u, v, w);
  56.     }
  57.  
  58.     // Shortest path
  59.     priority_queue<pair<std::int64_t, std::int64_t>, vector<pair<std::int64_t, std::int64_t>>, Compare> queue;
  60.  
  61.     queue.push(make_pair(source, 0));
  62.  
  63.     vector<bool> visited(V, false);
  64.     vector<std::int64_t> distances(V, DISTANCE_INITIALIZATION_VALUE);
  65.  
  66.     while (!queue.empty()) {
  67.         pair<std::int64_t, std::int64_t> curr = queue.top();
  68.         queue.pop();
  69.  
  70.         if (!visited.at(curr.first)) {
  71.             visited.at(curr.first) = true;
  72.             distances.at(curr.first) = curr.second;
  73.  
  74.             for (pair<std::int64_t, std::int64_t> neighbour : G.at(curr.first)) {
  75.                 if (!visited.at(neighbour.first)) {
  76.                     queue.push(make_pair(neighbour.first, curr.second + neighbour.second));
  77.                 }
  78.             }
  79.         }
  80.     }
  81.  
  82.     cout << distances.at(destination);
  83.     return 0;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement