b222困難

102 高雄市資訊學科能力競賽(2013)|動物排隊

dp[a][b][r]表示已放a隻雞、b隻鴨,形成餘數r的合法序列數。

解題思路

dp[a][b][r]表示已放a隻雞、b隻鴨,形成餘數r的合法序列數。

再放雞時餘數變2r modM;只有a>b才能放鴨,餘數變(2r+1) modM。這正是每隻鴨左邊雞較多的條件。

按總長度逐層轉移,最後將每個餘數乘上對應序列數並加總。方案數與總和使用任意精度。

時間 O(xyM),滾動依總長分層,空間 O(min(x,y)M)個計數;Python字典只保存可達狀態。

Step-by-step animation

教學小例:合法前綴與二進位餘數計數

回報動畫錯誤
步驟 1 / 3

x=2,y=1,M=4

合法排列001與010

合法排列001與010
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using boost::multiprecision::cpp_int;
int main() {
    int x, y, m;
    cin >> x >> y >> m;
    vector<vector<cpp_int>> cur(y + 1, vector<cpp_int>(m)), nxt;
    cur[0][0] = 1;
    for (int len = 0; len < x + y; len++) {
        nxt.assign(y + 1, vector<cpp_int>(m));
        for (int b = 0; b <= y; b++) {
            int a = len - b;
            if (a < 0 || a > x)
                continue;
            for (int r = 0; r < m; r++)
                if (cur[b][r] != 0) {
                    if (a < x)
                        nxt[b][2 * r % m] += cur[b][r];
                    if (b < y && a > b)
                        nxt[b + 1][(2 * r + 1) % m] += cur[b][r];
                }
        }
        cur.swap(nxt);
    }
    cpp_int ans = 0;
    for (int r = 0; r < m; r++)
        ans += cur[y][r] * r;
    cout << ans << '\n';
}

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

更多