Advertisement
Josif_tepe

Untitled

Dec 7th, 2021
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.30 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4. int n,m;
  5. int mat[100][100];
  6. int dp[100][100];
  7. pair<int, int> path[100][100];
  8. int rek(int i,int j)
  9. {
  10.     if(i==n-1  && j==n-1)
  11.     {
  12.         path[i][j] = make_pair(i, j);
  13.         return mat[i][j];
  14.     }
  15.     if(dp[i][j]!=-1)
  16.     {
  17.         return dp[i][j];
  18.     }
  19.     int maks=-2e9;
  20.     int desno = -2e9;
  21.     int dole = -2e9;
  22.     if(j+1<m)
  23.     {
  24.         desno = rek(i,j+1)+mat[i][j];
  25.     }
  26.     if(i+1<n)
  27.     {
  28.         dole = rek(i+1,j)+mat[i][j];
  29.     }
  30.     maks = max(desno, dole);
  31.     if(dole > desno) {
  32.         path[i][j] = make_pair(i + 1, j);
  33.     }
  34.     else {
  35.         path[i][j] = make_pair(i, j + 1);
  36.     }
  37.    
  38.     dp[i][j]=maks;
  39.     return maks;
  40. }
  41. int main()
  42. {
  43.     cin>>n>>m;
  44.     for(int i=0;i<n;i++)
  45.     {
  46.         for(int j=0;j<n;j++)
  47.         {
  48.             cin>>mat[i][j];
  49.         }
  50.     }
  51.     for(int i=0;i<n;i++)
  52.     {
  53.         for(int j=0;j<m;j++)
  54.         {
  55.             dp[i][j]=-1;
  56.         }
  57.     }
  58.     cout<<rek(0,0) << endl;
  59.    
  60.     for(pair<int, int> at = make_pair(0, 0); at != make_pair(n - 1, m - 1); at = make_pair(path[at.first][at.second].first, path[at.first][at.second].second)) {
  61.         cout << at.first  + 1<< " " << at.second + 1<< endl;
  62.     }
  63.     cout << n << " " << m << endl;
  64.     return 0;
  65. }
  66.  
  67.  
  68.  
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement