Advertisement
Josif_tepe

Untitled

Oct 17th, 2023
814
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.80 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4. int n, m;
  5. int mat[55][55];
  6. int dp[55][55];
  7. int max_sum(int i, int j) {
  8.     if(i == n - 1 and j == m - 1) {
  9.         return mat[i][j];
  10.     }
  11.     if(dp[i][j] != -1) {
  12.         return dp[i][j];
  13.     }
  14.     int result = 0;
  15.     if(i + 1 < n) {
  16.         result = max(result, max_sum(i + 1, j) + mat[i][j]);
  17.     }
  18.     if(j + 1 < m) {
  19.         result = max(result, max_sum(i, j + 1) + mat[i][j]);
  20.     }
  21.     return dp[i][j] = result;
  22. }
  23. int main() {
  24.     cin >> n >> m;
  25.    
  26.     for(int i = 0; i < n; i++) {
  27.         for(int j = 0; j < m; j++) {
  28.             cin >> mat[i][j];
  29.             dp[i][j] = -1;
  30.         }
  31.     }
  32.     cout << max_sum(0, 0) << endl;
  33.     return 0;
  34. }
  35. // f(0, 0) = f(1, 0) f(0, 1)
  36. // f(1, 0) = f(2, 0) f(1, 1)
  37. // f(0, 1) = f(1, 1) f(2, 0)
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement