b428中等

奇偶交替的精確總量

運用精確總和與最後奇偶的子序列 DP,正確求解本題並處理邊界情況。

解題思路

dp[parity][sum] 表示非空子序列、最後一個數奇偶為 parity、總和為 sum 的最大長度。

讀取 x 時,只由另一奇偶的舊狀態加上 x,也可用 x 自己開一段。略過元素則保留原狀態。

來源奇偶和目標奇偶不同,所以只寫入自身奇偶,不會在同一步重複使用 x,連 x=0 也安全。

時間 O(nS),空間 O(S+n)。

Step-by-step animation

教學例子:1、2、3、4、5,目標和9。

回報動畫錯誤
步驟 1 / 3

步驟 1

1、2、3、4、5,目標和9。

1
2
3
4
5
狀態
9

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, S;
    cin >> n >> S;
    vector<vector<int>> dp(2, vector<int>(S + 1, -1));
    while (n--) {
        int x;
        cin >> x;
        if (x > S)
            continue;
        int c = x % 2;
        for (int s = 0; s + x <= S; s++)
            if (dp[1 - c][s] >= 0)
                dp[c][s + x] = max(dp[c][s + x], dp[1 - c][s] + 1);
        dp[c][x] = max(dp[c][x], 1);
    }
    cout << max(dp[0][S], dp[1][S]) << '\n';
}

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

更多