Josif_tepe

Untitled

Jul 25th, 2025
907
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.96 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstring>
  3. using namespace std;
  4. int h;
  5. int w;
  6. int x[101][101];
  7. int dp[101][101];
  8. const int INF = 1e9;
  9. int rec(int i,int j){
  10.     if(i==h-1){
  11.         return x[i][j];
  12.     }
  13.     if(dp[i][j]!=-1){
  14.         return dp[i][j];
  15.     }
  16.     int res=-INF;
  17.     if(i + 1 < h){
  18.         res=max(res,rec(i+1,j)+x[i][j]);
  19.        
  20.         if(j + 1 < w) {
  21.             res=max(res,rec(i+1,j+1)+x[i][j]);
  22.         }
  23.        
  24.         if(j - 1 >= 0) {
  25.             res=max(res,rec(i+1,j-1)+x[i][j]);
  26.         }
  27.     }
  28.     dp[i][j]=res;
  29.     return res;
  30. }
  31. int main()
  32. {
  33.     int t;
  34.     cin>>t;
  35.     int a;
  36.     for(int i = 0;i<t;i++){
  37.         cin>>h>>w;
  38.         a=0;
  39.         memset(dp,-1,sizeof dp);
  40.         for(int j = 0;j<h;j++){
  41.             for(int k = 0;k<w;k++){
  42.                 cin>>x[j][k];
  43.             }
  44.         }
  45.         for(int l = 0;l<w;l++){
  46.             a=max(a,rec(0,l));
  47.         }
  48.         cout<<a << endl;
  49.     }
  50.     return 0;
  51. }
  52.  
Advertisement
Add Comment
Please, Sign In to add comment