Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <queue>
- using namespace std;
- const int N = 51;
- const int INF = 1e9;
- const int dx[4] = {0, 0, 1, -1};
- const int dy[4] = {1, -1, 0, 0};
- int a[N][N], n, m;
- int dist[N][N];
- int main()
- {
- cin >> n >> m;
- for (int i = 1; i <= n; i++) {
- for (int j = 1; j <= m; j++) {
- cin >> a[i][j];
- dist[i][j] = INF;
- }
- }
- dist[1][1] = 0;
- priority_queue<pair<int, pair<int, int>>> q;
- q.push({0, {1, 1}});
- while (!q.empty()) {
- auto [d, p] = q.top();
- auto [x, y] = p;
- q.pop();
- d = -d;
- if (d != dist[x][y])
- continue;
- for (int i = 0; i < 4; i++) {
- int ax = x + dx[i];
- int ay = y + dy[i];
- if (ax > 0 && ay > 0 && ax <= n && ay <= m) {
- int cost = 0;
- if (a[ax][ay] <= a[x][y])
- cost = abs(a[ax][ay] - a[x][y]);
- else
- cost = 3 * abs(a[ax][ay] - a[x][y]);
- if (dist[ax][ay] > dist[x][y] + cost) {
- dist[ax][ay] = dist[x][y] + cost;
- q.push({-dist[ax][ay], {ax, ay}});
- }
- }
- }
- }
- cout << dist[n][m];
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement