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]);
    }
    
}

 

转载于:https://www.cnblogs.com/yuanshixingdan/p/5566760.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值