a751困難重量 DP 中的選取人數位元集合
CPE:Tug of War (UVa 10032)
兼顧體重接近與兩隊人數平衡。
解題思路
只做可達重量的背包會忘記兩隊人數限制。令 masks[s] 的第 k 個位元表示能否選出恰好 k 人且總重 s,初始 masks[0]=1。加入體重 w 時,將 masks[s−w] 左移一位再 OR 到 masks[s];重量倒序保證每人僅選一次。
固定其中一隊人數為 floor(n/2),另一隊自然為 ceil(n/2)。掃描所有帶此人數位元的重量 s,選 |total−2s| 最小者,輸出 min(s,total−s) 和 max。n≤100,所以需要的位元最多 50,C++ unsigned long long 足夠,即使更高位截斷也不影響低位。第一行測試組數,組間輸出空行。
Step-by-step animation
示意:100,90,200,共 3 人
步驟 1 / 3
前兩人
可選一人得 90 或 100,選兩人得 190。
90:k1
100:k1
190:k2
- 目標人數
- 1
#include <iostream>
#include <vector>
#include <numeric>
#include <cstdlib>
#include <algorithm>
using namespace std;
int main() {
int t;
cin >> t;
for (int cs = 0; cs < t; ++cs) {
int n;
cin >> n;
vector<int> w(n);
for (int &v : w)
cin >> v;
int total = accumulate(w.begin(), w.end(), 0), used = 0;
vector<unsigned long long> dp(total + 1);
dp[0] = 1;
for (int v : w) {
used += v;
for (int s = used; s >= v; --s)
dp[s] |= dp[s - v] << 1;
}
int best = 0, diff = total + 1;
for (int s = 0; s <= total; ++s)
if ((dp[s] >> (n / 2)) & 1ULL)
if (abs(total - 2 * s) < diff) {
diff = abs(total - 2 * s);
best = s;
}
if (cs)
cout << '\n';
cout << min(best, total - best) << ' ' << max(best, total - best) << '\n';
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。