fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define int long long
  5. const int NEG = -4e18;
  6.  
  7. signed main() {
  8. ios::sync_with_stdio(false);
  9. cin.tie(nullptr);
  10.  
  11. int t;
  12. cin >> t;
  13. while (t--) {
  14. int n, m;
  15. cin >> n >> m;
  16.  
  17. vector<vector<int>> a(n, vector<int>(m));
  18. for (int i = 0; i < n; i++)
  19. for (int j = 0; j < m; j++)
  20. cin >> a[i][j];
  21.  
  22. vector<vector<int>> dp(n, vector<int>(m, NEG));
  23.  
  24. dp[0][0] = a[0][0];
  25. for (int i = 0; i < n; i++) {
  26. for (int j = 0; j < m; j++) {
  27. if (i == 0 && j == 0) continue;
  28. if (i > 0) dp[i][j] = max(dp[i][j], dp[i-1][j]);
  29. if (j > 0) dp[i][j] = max(dp[i][j], dp[i][j-1]);
  30. dp[i][j] += a[i][j];
  31. }
  32. }
  33.  
  34.  
  35. int i = n - 1, j = m - 1;
  36. int mn = LLONG_MAX;
  37.  
  38. while (true) {
  39. if (a[i][j] > 0)
  40. mn = min(mn, a[i][j]);
  41.  
  42. if (i == 0 && j == 0) break;
  43.  
  44. if (i > 0 && dp[i][j] == dp[i-1][j] + a[i][j]) {
  45. i--;
  46. } else {
  47. j--;
  48. }
  49. }
  50.  
  51. int ans = dp[n-1][m-1];
  52. if (mn != LLONG_MAX)
  53. ans -= 2 * mn;
  54.  
  55. cout << ans << '\n';
  56. }
  57. return 0;
  58. }
  59.  
Success #stdin #stdout 0.01s 5320KB
stdin
2
3 3
1 -2 3
4 -5 2
1 6 -1
2 4
-1 -1 -1 1
-1 -1 -1 -1
stdout
9
-5