解題思路
將禮品分成總價最接近的兩組。
總價S固定,若較小組為t≤S/2,差值是S−2t,所以只需找不超過S/2的最大可達子集合和。
逐件做0/1背包;C++金額倒序更新,Python以位元集合bits
= bits<<x表示加入這件後的新可達金額。
更新前後的可達集合分別代表不選與選當前禮品,歸納得到全部子集合和;取最大t後輸出t與S−t。
C++時間 O(nS)、空間 O(n+S)。Python位元運算約 O(nS/w)、空間 O(n+S),w為大整數每儲存字的位數。
Step-by-step animation
0/1 子集合和分割逐步追蹤
步驟 1 / 3
步驟 1
15、20、10、25,總價70,目標35。
S=70
half=35
- 步驟
- 1
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
int n, k;
cin >> n >> k;
vector<int> a(n);
int S = 0;
for (int &x : a) {
cin >> x;
S += x;
}
vector<char> d(S / 2 + 1);
d[0] = 1;
for (int x : a)
for (int j = S / 2; j >= x; j--)
d[j] |= d[j - x];
int t = S / 2;
while (!d[t])
t--;
cout << t << ' ' << S - t << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。