D_L3

SDA - hw11 - task1

Dec 16th, 2023
952
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.72 KB | None | 0 0
  1. #include <iostream>
  2. #include <unordered_map>
  3. #include <queue>
  4. #include <set>
  5. #include <climits>
  6. using namespace std;
  7.  
  8. int periods[10000];
  9. vector<int> distances(10000, INT_MAX);
  10.  
  11. unordered_map<int, unordered_map<int, int>> graph; //from, {to, cost}
  12.  
  13. int findShortest(int start, int end) {
  14.     set<pair<int, int>> queue; //minDist, idx
  15.     queue.insert({ 0, start });
  16.     while (!queue.empty())
  17.     {
  18.         auto curr = *queue.begin();
  19.         queue.erase(curr);
  20.  
  21.         if (curr.second == end)
  22.         {
  23.             return distances[curr.second];
  24.         }
  25.  
  26.         auto neighbours = graph[curr.second];
  27.         for (auto& neighbour : neighbours)
  28.         {
  29.             int waitingTime = (curr.first + neighbour.second) % periods[neighbour.first];
  30.             int finalTime = curr.first + neighbour.second;
  31.             if (waitingTime != 0 && neighbour.first != end)
  32.             {
  33.                 finalTime += periods[neighbour.first] - waitingTime;
  34.             }
  35.  
  36.             if (finalTime < distances[neighbour.first])
  37.             {
  38.                 queue.erase({ distances[neighbour.first], neighbour.first });
  39.                 queue.insert({ finalTime, neighbour.first });
  40.                 distances[neighbour.first] = finalTime;
  41.             }
  42.         }
  43.     }
  44.  
  45.     return -1;
  46. }
  47.  
  48. int main()
  49. {
  50.     int v, e, start, end, a, b, c;
  51.     cin >> v >> e >> start >> end;
  52.  
  53.     for (size_t i = 0; i < v; i++)
  54.     {
  55.         cin >> periods[i];
  56.     }
  57.  
  58.     for (size_t i = 0; i < e; i++)
  59.     {
  60.         cin >> a >> b >> c;
  61.         if (graph[a][b] == 0)
  62.         {
  63.             graph[a][b] = INT_MAX;
  64.         }
  65.         graph[a][b] = min(graph[a][b], c);
  66.     }
  67.  
  68.     cout << findShortest(start, end);
  69.    
  70. }
  71.  
Advertisement
Add Comment
Please, Sign In to add comment