lightoj-1145 - Dice (I)(dp计数)
1145 - Dice (I)
PDF (English) Statistics Forum
Time Limit: 2 second(s) Memory Limit: 32 MB
You have N dices; each of them has K faces numbered from 1 to K. Now you have arranged the N dices in a line. You can rotate/flip any dice if you want. How many ways you can set the top faces such that the summation of all the top faces equals S?
Now you are given N, K, S; you have to calculate the total number of ways.
Input
Input starts with an integer T (≤ 25), denoting the number of test cases.
Each case contains three integers: N (1 ≤ N ≤ 1000), K (1 ≤ K ≤ 1000) and S (0 ≤ S ≤ 15000).
Output
For each case print the case number and the result modulo 100000007.
Sample Input
Output for Sample Input
5
1 6 3
2 9 8
500 6 1000
800 800 10000
2 100 10
Case 1: 1
Case 2: 7
Case 3: 57286574
Case 4: 72413502
Case 5: 9
解题思路:定义dp[i][j] 表示摇了n个骰子,总和为j。
不难发现:dp[i][j] = dp[i-1][j-1] + ……+dp[i-1][max(0,j-k)]; 将所有i-1 层中能达到j的次数加起来 就是邀n个骰子能到j的次数
则 dp[i][j-1] = dp[i-1][j-2]+……+dp[i-1][max(0,j-k-1)];
合并得dp[i][j] = dp[i][j-1]+dp[i-1][j-1]-dp[i-1][max(0,j-k-1)];
因为要加mod ,所以式子写成dp[i][j] = (dp[i][j-1]+dp[i-1][j-1]-dp[i-1][max(0,j-k-1)]+mod)%mod;ps: 里面+mod 是因为可能出现减数的mod 大于前面2个的情况 此时要+mod 把他纠正为正数。
以上的状态转移足够解决这个问题,但是题目给的内存只有32MB 。 这样写会超限。
我们在分析下会发现,其实每次计算都只需要i-1,i 这两个状态,那么我们定义一个dp[2][j] 来滚动存储就可以了
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int mod = 100000007; long long dp[2][15010]; int main(){ int T,n,k,s; scanf("%d",&T); for(int t=1;t<=T;t++){ scanf("%d%d%d",&n,&k,&s); memset(dp,0,sizeof(dp)); for(int i=1;i<=k;i++) dp[1][i] = 1; for(int i=2;i<=n;i++){ for(int j=1;j<=s;j++){ dp[i%2][j] = (dp[i%2][j-1]+dp[(i+1)%2][j-1] - dp[(i+1)%2][max(0,j-k-1)]+mod)%mod; } //cout<<dp[i][s]<<endl; } printf("Case %d: %lld\n",t,dp[n%2][s]); } }