a738困難輪廓記憶搜尋與同類拼片去重
CPE:Tile Puzzle (UVa 798)
以唯一的下一空格固定拼片順序,精確計算矩形鋪排。
解題思路
從下往上填滿板面,用每欄已填高度 profile 表示輪廓。找高度最低且最左的一欄 x,其下一空格在任何完整鋪法中,必定由一片左下角在該位置的矩形覆蓋。嘗試每個仍有庫存的尺寸及旋轉;只有跨越的欄高度都相同、且不超出邊界時才能放入,然後提高這些欄。
同尺寸拼片只記剩餘數量,不能逐片編號;正方形只試一個方向,旋轉後相同的尺寸組先合併。以輪廓及各組剩餘數量為快取鍵,避免重算子問題,全部高度達 H 且庫存用完算 1 解。讀到 EOF。這是精確的指數級計數搜尋,題目只給板面上限而未限制狀態數,大面積且解法多時仍可能耗盡時間或記憶體;不能宣稱尺寸上限保證多項式效率。C++ 用十進位字串加法避免解數溢位。
Step-by-step animation
示意:2×2 板,兩片 1×2,答案 2
步驟 1 / 3
空板
兩欄高度都是 0,剩餘兩片。
0
0
- 庫存
- 2
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
#include <functional>
using namespace std;
string add(string a, const string &b) {
int i = int(a.size()) - 1, j = int(b.size()) - 1, carry = 0;
string out;
while (i >= 0 || j >= 0 || carry) {
int v = carry;
if (i >= 0)
v += a[i--] - '0';
if (j >= 0)
v += b[j--] - '0';
out += char('0' + v % 10);
carry = v / 10;
}
reverse(out.begin(), out.end());
return out;
}
int main() {
int W, H, n;
while (cin >> W >> H >> n) {
if (W > H)
swap(W, H);
map<pair<int, int>, int> groups;
while (n--) {
int m, w, h;
cin >> m >> w >> h;
if (w > h)
swap(w, h);
groups[{w, h}] += m;
}
vector<pair<int, int>> dim;
vector<int> left;
for (auto [d, m] : groups) {
dim.push_back(d);
left.push_back(m);
}
vector<int> root(W, 0);
root.insert(root.end(), left.begin(), left.end());
map<vector<int>, string> memo;
struct Frame {
vector<int> key;
size_t branch = 0;
string sum = "0";
};
vector<Frame> stack;
stack.push_back({root});
auto finish = [&](string value) {
memo[stack.back().key] = value;
stack.pop_back();
if (!stack.empty())
stack.back().sum = add(stack.back().sum, value);
};
// Explicit DFS frames avoid a call stack as deep as 10000 unit tiles.
while (!stack.empty()) {
Frame &frame = stack.back();
auto &key = frame.key;
int x = min_element(key.begin(), key.begin() + W) - key.begin(), y = key[x];
if (y == H) {
bool empty = true;
for (size_t k = 0; k < dim.size(); ++k)
if (key[W + k])
empty = false;
finish(empty ? "1" : "0");
continue;
}
bool descended = false;
while (frame.branch < 2 * dim.size()) {
size_t option = frame.branch++, k = option / 2;
int turn = option % 2;
auto [a, b] = dim[k];
if (!key[W + k] || (turn && a == b))
continue;
int w = turn ? b : a, h = turn ? a : b;
if (x + w > W || y + h > H)
continue;
bool ok = true;
for (int c = x; c < x + w; ++c)
if (key[c] != y)
ok = false;
if (!ok)
continue;
vector<int> child = key;
--child[W + k];
for (int c = x; c < x + w; ++c)
child[c] += h;
auto hit = memo.find(child);
if (hit != memo.end())
frame.sum = add(frame.sum, hit->second);
else {
stack.push_back({child});
descended = true;
break;
}
}
if (!descended)
finish(frame.sum);
}
cout << memo[root] << '\n';
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。