b373中等

CSES 1633|骰子組合(Dice Combinations)

以動態規劃逐步構成目標金額或點數。

解題思路

以動態規劃逐步構成目標金額或點數。

把骰子點數1到6視為六種硬幣,並區分投擲順序。依最後一次點數d分類,dp[s]=sum dp[s−d],只取s≥d的項。

空序列或空組合是湊成0的唯一方法,dp[0]=1;每次加總對10^9+7取模。

時間 O(6n),空間 O(n)。

Step-by-step animation

骰子序列計數逐步追蹤

回報動畫錯誤
步驟 1 / 3

步驟 1

總和1只有[1]。

dp1=1
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
    int x;
    cin >> x;
    vector<int> c{1, 2, 3, 4, 5, 6};
    sort(c.begin(), c.end());
    vector<int> d(x + 1);
    d[0] = 1;
    for (int s = 1; s <= x; s++)
        for (int v : c) {
            if (v > s)
                break;
            d[s] += d[s - v];
            if (d[s] >= 1000000007)
                d[s] -= 1000000007;
        }
    cout << d[x] << '\n';
}

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

更多