a673中等等分行李的 0/1 子集合和

CPE:Luggage (UVa 10664)

把分兩車問題轉為能否湊出總重的一半。

前往題目練習 →回報教學錯誤每組 k 件、總重 S,時間 O(kS),空間 O(S)。

解題思路

若總重 S 是奇數,兩車不可能等重;若為偶數,只要選出總重 S/2 的子集合,剩下的行李自動也重 S/2。用 reachable[s] 表示目前處理過的行李能否恰好湊出 s,初始只有 reachable[0] 為真。

每件重量 w 由大到小更新 s:reachable[s] |= reachable[s−w]。倒序使右側狀態仍屬於加入本行李之前,保證每件只能用一次。總重至多 200,這比枚舉 2^20 個子集合更直接。每筆行李由一整行界定,沒有件數,所以必須逐行讀而不是把所有整數混成一串。

Step-by-step animation

示意:1,2,3

回報動畫錯誤
步驟 1 / 3

放入 1

可達重量為 0、1。

0✓
1✓
2
3
目標
3

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <numeric>
using namespace std;
int main() {
    int tests;
    cin >> tests;
    string line;
    getline(cin, line);
    while (tests--) {
        getline(cin, line);
        istringstream in(line);
        vector<int> a;
        int x;
        while (in >> x)
            a.push_back(x);
        int sum = accumulate(a.begin(), a.end(), 0), target = sum / 2;
        vector<bool> dp(target + 1);
        dp[0] = true;
        for (int w : a)
            for (int s = target; s >= w; s--)
                dp[s] = dp[s] || dp[s - w];
        cout << (!(sum % 2) && dp[target] ? "YES" : "NO") << '\n';
    }
}

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

更多