Advertisement
cosenza987

Untitled

Dec 17th, 2023
754
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.20 KB | None | 0 0
  1. //Слава Україні, Героям слава
  2.  
  3. #include <bits/stdc++.h>
  4.  
  5. using namespace std;
  6.  
  7. int dx[] = {0, -1, 0, 1};
  8. int dy[] = {1, 0, -1, 0};
  9.  
  10. // right, up, left, down
  11.  
  12. const int N = 1000;
  13.  
  14. int dp[N][N][4][10];
  15.  
  16. using node = tuple<int, int, int, int, int>;
  17.  
  18. int main() {
  19.     ios_base::sync_with_stdio(false);
  20.     cin.tie(nullptr);
  21.     freopen("in.txt", "r", stdin);
  22.     freopen("out.txt", "w", stdout);
  23.     memset(dp, 63, sizeof(dp));
  24.     string s;
  25.     vector<string> v;
  26.     while(cin >> s) v.push_back(s);
  27.     int n = v.size(), m = v[0].size();
  28.     for(int i = 0; i < 4; i++) {
  29.         dp[0][0][i][0] = 0;
  30.     }
  31.     priority_queue<node, vector<node>, greater<node>> pq;
  32.     pq.emplace(0, 0, 0, 0, 0);
  33.     pq.emplace(0, 0, 0, 3, 0);
  34.     int ans = INT_MAX;
  35.     while(!pq.empty()) {
  36.         auto [k, a, b, c, d] = pq.top(); pq.pop();
  37.         if(a == n - 1 and b == m - 1) {
  38.             ans = min(ans, k);
  39.         }
  40.         if(dp[a][b][c][d] != k) continue;
  41.         if(d < 3) {
  42.             int x = a + dx[c], y = b + dy[c];
  43.             if(x >= 0 and x < n and y >= 0 and y < m and dp[x][y][c][d + 1] > k + v[x][y] - '0') {
  44.                 dp[x][y][c][d + 1] = k + v[x][y] - '0';
  45.                 pq.emplace(dp[x][y][c][d + 1], x, y, c, d + 1);
  46.             }
  47.             continue;
  48.         }
  49.         if(d < 9) {
  50.             int x = a + dx[c], y = b + dy[c];
  51.             if(x >= 0 and x < n and y >= 0 and y < m and dp[x][y][c][d + 1] > k + v[x][y] - '0') {
  52.                 dp[x][y][c][d + 1] = k + v[x][y] - '0';
  53.                 pq.emplace(dp[x][y][c][d + 1], x, y, c, d + 1);
  54.             }
  55.         }
  56.         int l = (c - 1 + 4) % 4, r = (c + 1) % 4;
  57.         int x = a + dx[l], y = b + dy[l];
  58.         if(x >= 0 and x < n and y >= 0 and y < m and dp[x][y][l][0] > k + v[x][y] - '0') {
  59.             dp[x][y][l][0] = k + v[x][y] - '0';
  60.             pq.emplace(dp[x][y][l][0], x, y, l, 0);
  61.         }
  62.         x = a + dx[r], y = b + dy[r];
  63.         if(x >= 0 and x < n and y >= 0 and y < m and dp[x][y][r][0] > k + v[x][y] - '0') {
  64.             dp[x][y][r][0] = k + v[x][y] - '0';
  65.             pq.emplace(dp[x][y][r][0], x, y, r, 0);
  66.         }
  67.     }
  68.     cout << ans << "\n";
  69.     return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement