Advertisement
MaxObznyi

H

Jun 11th, 2022
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <queue>
  5. using namespace std;
  6.  
  7. const int N = 51;
  8. const int INF = 1e9;
  9.  
  10. const int dx[4] = {0, 0, 1, -1};
  11. const int dy[4] = {1, -1, 0, 0};
  12.  
  13. int a[N][N], n, m;
  14. int dist[N][N];
  15.  
  16.  
  17. int main()
  18. {
  19. cin >> n >> m;
  20. for (int i = 1; i <= n; i++) {
  21. for (int j = 1; j <= m; j++) {
  22. cin >> a[i][j];
  23. dist[i][j] = INF;
  24. }
  25. }
  26. dist[1][1] = 0;
  27. priority_queue<pair<int, pair<int, int>>> q;
  28. q.push({0, {1, 1}});
  29. while (!q.empty()) {
  30. auto [d, p] = q.top();
  31. auto [x, y] = p;
  32. q.pop();
  33. d = -d;
  34. if (d != dist[x][y])
  35. continue;
  36. for (int i = 0; i < 4; i++) {
  37. int ax = x + dx[i];
  38. int ay = y + dy[i];
  39. if (ax > 0 && ay > 0 && ax <= n && ay <= m) {
  40. int cost = 0;
  41. if (a[ax][ay] <= a[x][y])
  42. cost = abs(a[ax][ay] - a[x][y]);
  43. else
  44. cost = 3 * abs(a[ax][ay] - a[x][y]);
  45.  
  46. if (dist[ax][ay] > dist[x][y] + cost) {
  47. dist[ax][ay] = dist[x][y] + cost;
  48. q.push({-dist[ax][ay], {ax, ay}});
  49. }
  50. }
  51. }
  52. }
  53. cout << dist[n][m];
  54. return 0;
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement