b339中等

94 臺北市資訊學科能力競賽(2005)|鋪磁磚問題

計算左上缺角3×n棋盤的骨牌鋪法。

解題思路

計算左上缺角3×n棋盤的骨牌鋪法。

用3位遮罩記錄當前欄已被左側橫骨牌占用的格,首欄另把左上角標為已占。

在當前欄找第一個未占格,嘗試往下放直骨牌或往右放橫骨牌;後者在下一欄遮罩標對應列。

當前欄全滿就把方式加入下一欄的遮罩。每種完整鋪法在第一空格的位置有唯一選擇,遞迴不重複且不漏;最後只能接受沒有向右伸出的遮罩0。

每筆時間 O(n×8×常數),工作空間 O(8)狀態與深度3遞迴。Python一次split另需 O(q)查詢儲存;n≤41答案可用64位元。

Step-by-step animation

三列骨牌的輪廓動態規劃逐步追蹤

回報動畫錯誤
步驟 1 / 3

步驟 1

n=3,首欄左上角預設占用。

首欄mask=001
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
    int n;
    while (cin >> n) {
        array<ll, 8> d{};
        d[0] = 1;
        for (int c = 0; c < n; c++) {
            array<ll, 8> e{};
            function<void(int, int, ll)> fill = [&](int mask, int next, ll count) {
                int r = 0;
                while (r < 3 && (mask >> r & 1))
                    r++;
                if (r == 3) {
                    e[next] += count;
                    return;
                }
                if (r + 1 < 3 && !(mask >> (r + 1) & 1))
                    fill(mask | (3 << r), next, count);
                if (c + 1 < n)
                    fill(mask | (1 << r), next | (1 << r), count);
            };
            for (int m = 0; m < 8; m++)
                if (d[m]) {
                    if (c == 0 && (m & 1))
                        continue;
                    fill(m | (c == 0 ? 1 : 0), 0, d[m]);
                }
            d = e;
        }
        cout << d[0] << '\n';
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多