Advertisement
ivangarvanliev

Untitled

Feb 18th, 2025
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.06 KB | None | 0 0
  1. #include <iostream>
  2. #include <queue>
  3. #include <vector>
  4. #include <limits.h>
  5. #include <cmath>
  6.  
  7. using namespace std;
  8.  
  9. struct Point {
  10.     int x, y, time, cost;
  11.     bool operator>(const Point& other) const {
  12.         return time > other.time || (time == other.time && cost > other.cost);
  13.     }
  14. };
  15.  
  16. int r, k, m, t;
  17. vector<vector<char>> city;
  18. vector<Point> metroStations;
  19.  
  20. int dx[] = {-1, 1, 0, 0};
  21. int dy[] = {0, 0, -1, 1};
  22.  
  23. int bfs(int startX, int startY, int endX, int endY) {
  24.     priority_queue<Point, vector<Point>, greater<Point>> pq;
  25.     vector<vector<vector<int>>> visited(r, vector<vector<int>>(k, vector<int>(2, INT_MAX)));
  26.      
  27.     pq.push({startX, startY, 0, 0});
  28.     visited[startX][startY][0] = 0;
  29.      
  30.     while (!pq.empty()) {
  31.         Point current = pq.top();
  32.         pq.pop();
  33.          
  34.         int x = current.x, y = current.y, time = current.time, cost = current.cost;
  35.  
  36.         if (x == endX && y == endY) return cost;
  37.          
  38.         for (int i = 0; i < 4; i++) {
  39.             int nx = x + dx[i];
  40.             int ny = y + dy[i];
  41.             if (nx >= 0 && nx < r && ny >= 0 && ny < k && city[nx][ny] != '#') {
  42.                 int newCost = cost;
  43.                 int newTime = time + 5;
  44.                  
  45.                 if (city[nx][ny] == 'M') newTime = time + 1;
  46.                 if (visited[nx][ny][0] > newTime) {
  47.                     pq.push({nx, ny, newTime, newCost});
  48.                     visited[nx][ny][0] = newTime;
  49.                 }
  50.             }
  51.         }
  52.     }
  53.     return -1;
  54. }
  55.  
  56. int main() {
  57.     cin >> r >> k >> m >> t;
  58.      
  59.     city.resize(r, vector<char>(k));
  60.      
  61.     int startX, startY, endX, endY;
  62.     for (int i = 0; i < r; i++) {
  63.         for (int j = 0; j < k; j++) {
  64.             cin >> city[i][j];
  65.             if (city[i][j] == 'T') {
  66.                 startX = i;
  67.                 startY = j;
  68.             }
  69.             if (city[i][j] == 'K') {
  70.                 endX = i;
  71.                 endY = j;
  72.             }
  73.         }
  74.     }
  75.      
  76.     cout << bfs(startX, startY, endX, endY) << endl;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement