Dollar Dayz
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions:8242 | Accepted: 3082 |
Description
Farmer John goes to Dollar Days at The Cow Store and discovers an unlimited number of tools on sale. During his first visit, the tools are selling variously for $1, $2, and $3. Farmer John has exactly $5 to spend. He can buy 5 tools at $1 each or 1 tool at
$3 and an additional 1 tool at $2. Of course, there are other combinations for a total of 5 different ways FJ can spend all his money on tools. Here they are:
1 @ US$3 + 1 @ US$2 1 @ US$3 + 2 @ US$1 1 @ US$2 + 3 @ US$1 2 @ US$2 + 1 @ US$1 5 @ US$1Write a program than will compute the number of ways FJ can spend N dollars (1 <= N <= 1000) at The Cow Store for tools on sale with a cost of $1..$K (1 <= K <= 100).
Input
A single line with two space-separated integers: N and K.
Output
A single line with a single integer that is the number of unique ways FJ can spend his money.
Sample Input
5 3
Sample Output
5
dp[i][j]表示花j元从前i种工具中购买的方法数 则有两种情况, 1.第i种工具的花费大于j则不能买第i种,dp[i][j]=dp[i-1][j]。 2.可以买第i种,则dp[i][j]=dp[i-1][j]+dp[i][j-1]。 注意因为此数较大,会超过 long long 的范围,因此用大数运算 而开三维数组可能会导致内存过大,所以此处dp使用滚动数组。 代码: #include<iostream> #include<string> #include<string.h> #include<algorithm> #include<cstdio> int dp[2][1002][40]; using namespace std; int main() { int n,m; while(~scanf("%d%d",&n,&m)) { int i,j,k; memset(dp,0,sizeof(dp)); for(i=0; i<2; i++) dp[i][0][0]=1; for(i=1; i<=m; i++) { for(j=1; j<=n; j++) { if(j>=i) { int x=0; for(k=0;k<40;k++) { dp[i%2][j][k]=dp[(i-1)%2][j][k]+dp[i%2][j-i][k]+x; x=dp[i%2][j][k]/10; dp[i%2][j][k]%=10; } } else { for(k=0;k<40;k++) dp[i%2][j][k]=dp[(i-1)%2][j][k]; } } } int L=39; while(dp[m%2][n][L]==0) L--; for(i=L;i>=0;i--) printf("%d",dp[m%2][n][i]); } return 0; }