b417中等

障礙板上的直立骨牌

運用兩列輪廓 DP 與直立數量,正確求解本題並處理邊界情況。

解題思路

逐欄處理,mask 的兩個位元表示前一欄水平骨牌已伸入的格子,DP 再記用過幾個直立骨牌。

先排除伸入格與障礙重疊的狀態,再遞迴填這欄最上方的空格:可向下一格直立,或向右水平並設定下一欄 mask。

兩格都填完後轉移到下一欄;最後只接受 mask=0、直立數=K。每種鋪法的逐欄填法唯一,所以不重複。

時間 O(nK),每欄固定 4 個 mask 與常數填法;空間 O(n+K)。

Step-by-step animation

教學例子:2×4 全空板,恰兩個直立骨牌。

回報動畫錯誤
步驟 1 / 3

步驟 1

2×4 全空板,恰兩個直立骨牌。

....
....
狀態
K=2

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, K;
    cin >> n >> K;
    string a, b;
    cin >> a >> b;
    const int M = 1000000007;
    vector<vector<long long>> dp(4, vector<long long>(K + 1));
    dp[0][0] = 1;
    for (int col = 0; col < n; col++) {
        int block = (a[col] == '#') + 2 * (b[col] == '#');
        vector<vector<long long>> nd(4, vector<long long>(K + 1));
        for (int mask = 0; mask < 4; mask++)
            if (!(mask & block))
                for (int k = 0; k <= K; k++)
                    if (dp[mask][k]) {
                        function<void(int, int, int)> fill = [&](int used, int out,
                                                                 int cnt) {
                            if (cnt > K)
                                return;
                            if (used == 3) {
                                nd[out][cnt] = (nd[out][cnt] + dp[mask][k]) % M;
                                return;
                            }
                            int r = (used & 1) ? 1 : 0;
                            int bit = 1 << r;
                            if (r == 0 && !(used & 2))
                                fill(3, out, cnt + 1);
                            if (col + 1 < n)
                                fill(used | bit, out | bit, cnt);
                        };
                        fill(mask | block, 0, k);
                    }
        dp.swap(nd);
    }
    cout << dp[0][K] << '\n';
}

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

更多