LightOJ 1193 Dice (II)

本文探讨了一道经典的动态规划问题,即计算N个K面骰子排列组合使得其顶面之和为S时所有可能得分的总和。文章提供了一个高效的解决方案,并通过代码实现展示了如何使用动态规划来解决此类问题。
1193 - Dice (II)
Time Limit: 3 second(s)Memory Limit: 32 MB

You have N dices; each of them has K faces numbered from 1 to K. Now you can arrange the N dices in a line. If the summation of the top faces of the dices is S, you calculate the score as the multiplication of all the top faces.

Now you are given N, K, S; you have to calculate the summation of all the scores.

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) 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: 3

Case 2: 84

Case 3: 74335590

Case 4: 33274428

Case 5: 165


分析:详细分析见http://blog.youkuaiyun.com/gotoac/article/details/8967768

dp[i][j]:表示前i个骰子组成和为j时的所有乘积和(dp[n][s]即所求答案)

由题可知:

dp[i][j]=dp[i-1][j-1]+dp[i-1][j-2]*2+dp[i-1][j-3]*3+...+dp[i-1][j-k]*k

          =dp[i-1][j-1]+dp[i-1][j-2]+dp[i-1][j-3]+...+dp[i-1][j-k]  +

                             dp[i-1][j-2]+dp[i-1][j-3]+...+dp[i-1][j-k]  +

                                             dp[i-1][j-3]+...+dp[i-1][j-k]  +

                                                                   dp[i-1][j-k]  ;

进一步化简:

sum[i][j]=dp[i][1]+dp[i][2]+dp[i][3]+...+dp[i][j];  (表示前i个骰子组成和为1~j时的所有乘积和)

dp[i][j]=sum[i-1][j-1]-sum[i-1][j-k-1] +

            sum[i-1][j-2]-sum[i-1][j-k-1] +

            sum[i-1][j-3]-sum[i-1][j-k-1] +

             ...

             sum[i-1][j-k]-sum[i-1][j-k-1]  ;

继续化简:ssum[j]=sum[i-1][1]+sum[i-1][2]+sum[i-1][3]+...+sum[i-1][j-1];

dp[i][j]=ssum[j]-sum[j-k]-sum[i-1][j-k-1]*k;


最后滚动数组解决空间问题,总的时间复杂度O(n*s)

#include<cstdio>
#define ll long long
const int M=100000007;
const int N=15001;
ll dp[2][N],sum[2][N],ssum[N];
int main(){
	int n,k,s,i,j,T,ca=1;
	scanf("%d",&T);
	while(T--){
		scanf("%d%d%d",&n,&k,&s);
		printf("Case %d: ",ca++);
		if(s<n||s>n*k){puts("0");continue;}
		for(i=1;i<=s;i++)dp[0][i]=(i>k?0:i),sum[0][i]=(sum[0][i-1]+dp[0][i])%M;
		int now=0;
		for(i=2;i<=n;i++){
			now^=1,ssum[1]=0;
			for(j=1;j<=s;j++){
				if(j<=k)dp[now][j]=ssum[j];
				else dp[now][j]=((ssum[j]-ssum[j-k]-sum[now^1][j-k-1]*k)%M+M)%M;
				sum[now][j]=(sum[now][j-1]+dp[now][j])%M;
				ssum[j+1]=(ssum[j]+sum[now^1][j])%M;
			}
		}
		printf("%lld\n",dp[now][s]);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值