a700困難木棒子集合與正方形邊長回溯
CPE:Square (UVa 10364)
以已使用木棒遮罩記憶化,逐邊湊出相同長度。
解題思路
總長必須被4整除,且最長木棒不得超過side=總長/4。將木棒由長到短排列,逐根選進目前正在組的邊,累積fill不得超過side;恰滿時將fill歸0,開始下一邊。所有棒都用完即成功,因總長固定,此時一定完成四邊。
以mask表示已使用棒,fill其實由已選棒長總和模side唯一決定,記憶化可避免不同選取順序重算同一子集合。每層相同長度的未用棒只嘗試一根;開始空邊時,可固定放入最長未用棒,因四條邊沒有區別,必可把含該棒的邊排為下一邊。這些剪枝不漏解,M≤20使遮罩搜尋可行。輸出小寫yes或no。
Step-by-step animation
示意:木棒 2,2,1,1,1,1,side=2
步驟 1 / 3
前兩邊
兩根2各自完成一邊。
邊1:2
邊2:2
邊3:0
邊4:0
- 已用棒
- 2
- fill
- 0
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <functional>
using namespace std;
int main() {
int tests;
cin >> tests;
while (tests--) {
int n;
cin >> n;
vector<int> a(n);
for (int &x : a)
cin >> x;
sort(a.rbegin(), a.rend());
int total = accumulate(a.begin(), a.end(), 0), side = total / 4;
if (total % 4 || a[0] > side) {
cout << "no\n";
continue;
}
int full = (1 << n) - 1;
vector<signed char> memo(1 << n, -1);
function<bool(int, int)> dfs = [&](int mask, int fill) {
if (mask == full)
return true;
if (memo[mask] != -1)
return memo[mask] == 1;
int previous = -1;
for (int i = 0; i < n; i++)
if (!(mask >> i & 1) && a[i] != previous) {
previous = a[i];
if (fill + a[i] > side)
continue;
if (dfs(mask | (1 << i), (fill + a[i]) % side)) {
memo[mask] = 1;
return true;
}
if (fill == 0)
break;
}
memo[mask] = 0;
return false;
};
cout << (dfs(0, 0) ? "yes" : "no") << '\n';
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。