解題思路
求任意起終點、只能右下移動的最高分。
令dp[r][c]為結尾在(r,c)的最佳非空路徑。最後一步來自上方、左方,或這格本身就是起點。
因此dp=score+max(0,上方dp,左方dp);0代表重新起步,不是把空路徑當成答案。
逐列以一維陣列更新並維護所有格dp的最大值,每條合法路徑都有終點,所以最大值涵蓋全部起終點。
時間 O(mn),額外空間 O(n),逐行輸入另需O(n);不存m×n完整表。
Step-by-step animation
題面3×4原圖路徑3→−1→8→6
步驟 1 / 3
步驟 1
原圖第二列第一格3作為起點。
3
- 步驟
- 1
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int m, n;
cin >> m >> n;
vector<int> d(n);
int ans = INT_MIN;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
int x;
cin >> x;
d[j] = x + max({0, d[j], j ? d[j - 1] : 0});
ans = max(ans, d[j]);
}
cout << ans << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。