a146中等等重二分的 0/1 子集合和

TOI 2024/09 潛力組:天秤

由全部砝碼的半總重判斷兩堆是否能平衡。

前往題目練習 →回報教學錯誤S≤100000、目標≤50000。C++ 時間 O(NS)、空間 O(S);Python 位元集合約 O(NS/word) 個機器字操作、O(S) 位元,另需 O(N) 存輸入。

解題思路

所有砝碼都必須使用,若總重 S 是奇數就不可能平分。若 S 是偶數,只要找到一個子集合總重 S/2,剩下所有砝碼的總重也會自動是 S/2,不必同時追蹤兩堆。

C++ 令 reachable[s] 記錄能否用已讀砝碼湊出 s,每件 w 由大到小更新 reachable[s] |= reachable[s−w],確保每件最多一次。Python 用整數位元集合,bit s=1 表示 s 可達,每件更新 bits |= bits<<w,右側只依賴更新前的集合;遮罩保留到 S/2 即可。兩者都把選或不選一件的狀態取聯集。

Step-by-step animation

公開範例:2,3,4,5,目標 7

回報動畫錯誤
步驟 1 / 3

加入 2 與 3

從 {0} 開始,可達重量成為 {0,2,3,5}。

0
2
3
5
target
7

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
int main() {
    int n;
    cin >> n;
    vector<int> w(n);
    for (auto &x : w)
        cin >> x;
    int total = accumulate(w.begin(), w.end(), 0);
    if (total % 2) {
        cout << "0\n";
        return 0;
    }
    int target = total / 2;
    vector<unsigned char> reachable(target + 1, 0);
    reachable[0] = 1;
    for (int x : w)
        for (int s = target; s >= x; --s)
            reachable[s] |= reachable[s - x];
    cout << int(reachable[target]) << '\n';
}

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

更多