Advertisement
Guest User

Untitled

a guest
Jun 19th, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. /*
  2. Problem 1:
  3. The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon.
  4. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned
  5. in the top-left room and must fight his way through the dungeon to rescue the princess.
  6. The knight has an initial health point represented by a positive integer. If at any point his health point
  7. drops to 0 or below, he dies immediately.
  8. Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these
  9. rooms; other rooms are either empty (0’s) or contain magic orbs that increase the knight’s health (positive integers).
  10. In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.
  11.  
  12. Write a function to determine the knight’s minimum initial health so that he is able to rescue the princess.
  13. For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path
  14. RIGHT-> RIGHT -> DOWN -> DOWN.
  15. -2(K) -3 3
  16. -5 -10 1
  17. 10 30 -5(P)
  18. */
  19. #include <bits/stdc++.h>
  20.  
  21. #define inp(x) scanf("%d",&x)
  22. #define loop(i,n) for(int i=0;i<n;++i)
  23. #define rloop(i,n) for(int i=n-1;i>=0;--i)
  24. #define pb push_back
  25. #define mp make_pair
  26. #define ll long long
  27.  
  28. using namespace std;
  29. //-------------------------------------------------//
  30.  
  31. int m, n;
  32. int getMinHP(vector<vector<int>> a, vector<vector<int>> &c, int i, int j){
  33.  
  34. if(c[i][j] != -1)
  35. return c[i][j];
  36. if(i == m-1)
  37. return c[i][j] = max(0, getMinHP(a, c, i, j+1) - a[i][j]);
  38. if(j == n-1)
  39. return c[i][j] = max(0, getMinHP(a, c, i+1, j) - a[i][j]);
  40.  
  41. return c[i][j] = min(
  42. max(0, getMinHP(a, c, i, j+1) - a[i][j]),
  43. max(0, getMinHP(a, c, i+1, j) - a[i][j])
  44. );
  45. }
  46.  
  47. int main(){
  48. cin >> m >> n;
  49. vector<vector<int>> a(m, vector<int> (n, 0));
  50. vector<vector<int>> c(m, vector<int> (n, -1));
  51. for(int i = 0; i < m; ++i)
  52. for(int j = 0; j < n; ++j)
  53. cin >> a[i][j];
  54.  
  55. c[m-1][n-1] = max(0, 1 - a[m-1][n-1]);
  56. cout << getMinHP(a, c, 0, 0) << endl;
  57.  
  58. //Debug
  59. // for(int i = 0; i < m; ++i,cout << endl)
  60. // for(int j = 0; j < n; ++j)
  61. // cout << c[i][j] << " ";
  62.  
  63. return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement