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