a146中等等重二分的 0/1 子集合和
TOI 2024/09 潛力組:天秤
由全部砝碼的半總重判斷兩堆是否能平衡。
解題思路
所有砝碼都必須使用,若總重 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
#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';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。