Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Слава Україні, Героям слава
- #include <bits/stdc++.h>
- using namespace std;
- int dx[] = {0, -1, 0, 1};
- int dy[] = {1, 0, -1, 0};
- // right, up, left, down
- const int N = 1000;
- int dp[N][N][4][10];
- using node = tuple<int, int, int, int, int>;
- int main() {
- ios_base::sync_with_stdio(false);
- cin.tie(nullptr);
- freopen("in.txt", "r", stdin);
- freopen("out.txt", "w", stdout);
- memset(dp, 63, sizeof(dp));
- string s;
- vector<string> v;
- while(cin >> s) v.push_back(s);
- int n = v.size(), m = v[0].size();
- for(int i = 0; i < 4; i++) {
- dp[0][0][i][0] = 0;
- }
- priority_queue<node, vector<node>, greater<node>> pq;
- pq.emplace(0, 0, 0, 0, 0);
- pq.emplace(0, 0, 0, 3, 0);
- int ans = INT_MAX;
- while(!pq.empty()) {
- auto [k, a, b, c, d] = pq.top(); pq.pop();
- if(a == n - 1 and b == m - 1) {
- ans = min(ans, k);
- }
- if(dp[a][b][c][d] != k) continue;
- if(d < 3) {
- int x = a + dx[c], y = b + dy[c];
- if(x >= 0 and x < n and y >= 0 and y < m and dp[x][y][c][d + 1] > k + v[x][y] - '0') {
- dp[x][y][c][d + 1] = k + v[x][y] - '0';
- pq.emplace(dp[x][y][c][d + 1], x, y, c, d + 1);
- }
- continue;
- }
- if(d < 9) {
- int x = a + dx[c], y = b + dy[c];
- if(x >= 0 and x < n and y >= 0 and y < m and dp[x][y][c][d + 1] > k + v[x][y] - '0') {
- dp[x][y][c][d + 1] = k + v[x][y] - '0';
- pq.emplace(dp[x][y][c][d + 1], x, y, c, d + 1);
- }
- }
- int l = (c - 1 + 4) % 4, r = (c + 1) % 4;
- int x = a + dx[l], y = b + dy[l];
- if(x >= 0 and x < n and y >= 0 and y < m and dp[x][y][l][0] > k + v[x][y] - '0') {
- dp[x][y][l][0] = k + v[x][y] - '0';
- pq.emplace(dp[x][y][l][0], x, y, l, 0);
- }
- x = a + dx[r], y = b + dy[r];
- if(x >= 0 and x < n and y >= 0 and y < m and dp[x][y][r][0] > k + v[x][y] - '0') {
- dp[x][y][r][0] = k + v[x][y] - '0';
- pq.emplace(dp[x][y][r][0], x, y, r, 0);
- }
- }
- cout << ans << "\n";
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement