fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int max(int a,int b,int c){
  4. if(a>b && a>c)
  5. return a;
  6. else if(b>a && b>c)
  7. return b;
  8. else
  9. return c;
  10. }
  11.  
  12. int main(){
  13. int t;
  14. cin>>t;
  15. while(t--){
  16. int h,w;
  17. cin>>h>>w;
  18. int dp[h][w];
  19. for(int i=0;i<h;i++)
  20. for(int j=0;j<w;j++)
  21. cin>>dp[i][j];
  22. for(int i=1;i<h;i++){
  23. for(int j=0;j<w;j++){
  24. if(j==0)
  25. dp[i][j] = dp[i][j]+ std::max(dp[i-1][j],dp[i-1][j+1]);
  26. else if(j==w-1 && j-1>=0)
  27. dp[i][j] = dp[i][j] + std::max(dp[i-1][j],dp[i-1][j-1]);
  28. else
  29. dp[i][j] = dp[i][j] + max(dp[i-1][j-1],dp[i-1][j],dp[i-1][j+1]);
  30. }
  31. }
  32. int ans=dp[h-1][0];
  33.  
  34. for(int j=1;j<w;j++){
  35. if(dp[h-1][j]>ans)
  36. ans = dp[h-1][j];
  37. }
  38. cout<<ans<<"\n";
  39. }
  40. return 0;
  41. }
  42.  
Success #stdin #stdout 0s 15232KB
stdin
1
6 5
3 1 7 4 2
2 1 3 1 1
1 2 2 1 8
2 2 1 5 3
2 1 4 4 4
5 2 7 5 1
stdout
32