fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5. ios::sync_with_stdio(false);
  6. cin.tie(nullptr);
  7.  
  8. int M, N;
  9. cin >> M >> N;
  10.  
  11. vector<vector<int>> a(M + 2, vector<int>(N + 2));
  12. for (int i = 1; i <= M; i++)
  13. for (int j = 1; j <= N; j++)
  14. cin >> a[i][j];
  15.  
  16. const long long NEG = -4e18;
  17. vector<vector<long long>> dp(M + 2, vector<long long>(N + 2, NEG));
  18.  
  19.  
  20. for (int i = 1; i <= M; i++)
  21. dp[i][1] = a[i][1];
  22.  
  23.  
  24. for (int j = 2; j <= N; j++) {
  25. for (int i = 1; i <= M; i++) {
  26. dp[i][j] = a[i][j] + max({ dp[i][j-1],
  27. dp[i-1][j-1],
  28. dp[i+1][j-1] });
  29. }
  30. }
  31.  
  32.  
  33. long long ans = NEG;
  34. for (int i = 1; i <= M; i++)
  35. ans = max(ans, dp[i][N]);
  36.  
  37. cout << ans;
  38. return 0;
  39. }
  40.  
Success #stdin #stdout 0.01s 5316KB
stdin
4 4
1 1 1 -3
-3 -3 -1 3
-3 2 -3 2
-1 2 -3 -3
stdout
6