CSES Dice Combinations 題解
DP? 想成高中數學的遞迴就好啦
題目
- Time limit: 1.00 s
- Memory limit: 512 MB
Your task is to count the number of ways to construct sum n by throwing a dice one or more times. Each throw produces an outcome between 1 and 6.
For example, if n=3, there are 4 ways:
- 1+1+1
- 1+2
- 2+1
- 3
| Input | Output |
|---|---|
| The only input line has an integer . | Print the number of ways modulo . |
Constraints
Example:
| Input | Output |
|---|---|
| 3 | 4 |
解法
分析
這是DP入門題
給定,令表示欲求的方法數。
首先處理的情形,此時是整數的有序拆分
(時就不是了,以作為舉例,直接算整數拆分的方法數會多算到「擲出一個」這個方法,但骰子點數只有~)
對於整數的整數拆分,可以看成有顆球一字排開,如此共有個空隙,每個空隙都可選擇放/不放一個隔板,此方法數與整數拆分方法數一一對應。如此共有種方法。
而當,欲組出總和為,可以是以下幾種情形:
- 前幾次已組出,最後一次擲出
- 前幾次已組出,最後一次擲出
- 前幾次已組出,最後一次擲出
等等,一直到
- 前幾次已組出,最後一次擲出
於是
喔然後記得模
AC Code
#include<bits/stdc++.h>
using namespace std;
const int M = 1e9+7;
const int N_MAX = 1e6;
long long dp[N_MAX+1];
int main(){
int n;
cin >> n;
for(int i=1;i<=6;i++){dp[i] = 1 << (i-1);}
for(int i=7;i<=n;i++){
for(int j=1;j<=6;j++){
dp[i] = (dp[i] + dp[i-j]) % M;
}
}
cout << dp[n];
}
這裡用了一個技巧,1 << (i-1)。其中<<是左移算子,表示在二進位表示中將整個數字往左移i-1格,然後在後面補。
比如1 << 5的結果等於。所以1 << (i-1)其實就是的意思。
本部落格所有文章除特別聲明外,均採用CC BY-NC-SA 4.0 授權協議。轉載請註明來源 R3X's Blog!


![[Note] Writing a simple Program in C - LiveOverflow](/2026/06/03/Note-Writing-a-simple-Program-in-C-LiveOverflow/output.png)