b060中等

107 臺北市資訊學科能力競賽(2018)|幸運表格(Lucky)

從每格求走到邊界外的最大總和。

解題思路

dp[r][c]=格值+max(右方後續,下方後續),表格外的後續為0,因為走出去後不再吃到任何值。

由右下往左上計算,兩個後繼都已完成。內部格子不能直接選0終止;只有右方或下方真的在圖外時才可使用0。

所有合法路徑的起點都在某格,因此答案是全表dp最大值,而非只取左上,也不能把全負答案改成0。

時間 O(mn),儲存圖O(mn),滾動DP O(n)。

Step-by-step animation

反向路徑 DP 與強制離開|2×2值1,−9/−9,−2,右下dp=−2。

回報動畫錯誤
步驟 1 / 3

右下

2×2值1,−9/−9,−2,右下dp=−2。

1
−9
−9
−2
dp右下
−2

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    int m, n;
    cin >> m >> n;
    vector<vector<int>> a(m, vector<int>(n));
    for (auto &r : a)
        for (int &x : r)
            cin >> x;
    vector<int> d(n + 1);
    int ans = INT_MIN;
    for (int r = m - 1; r >= 0; r--)
        for (int c = n - 1; c >= 0; c--) {
            d[c] = a[r][c] + max(d[c], d[c + 1]);
            ans = max(ans, d[c]);
        }
    cout << ans << "\n";
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多