Dollars |
New Zealand currency consists of $100, $50, $20, $10, and $5 notes and $2, $1, 50c, 20c, 10c and 5c coins. Write a program that will determine, for any given amount, in how many ways that amount may be made up. Changing the order of listing does not increase the count. Thus 20c may be made up in 4 ways: 1 20c, 2 10c, 10c+2 5c, and 4 5c.
Input
Input will consist of a series of real numbers no greater than $300.00 each on a separate line. Each amount will be valid, that is will be a multiple of 5c. The file will be terminated by a line containing zero (0.00).
Output
Output will consist of a line for each of the amounts in the input, each line consisting of the amount of money (with two decimal places and right justified in a field of width 6), followed by the number of ways in which that amount may be made up, right justified in a field of width 17.
Sample input
0.20 2.00 0.00
Sample output
0.20 4 2.00 293
动态规划问题,难点在于硬币的组合方式是不能重复的。
设数组dp[i]表示组合出 i 这么大的面值的方法数
硬币一共有从小到大11种面值,保存在num[i]数组中
这样对于每一个num[i],我们可以得到如下的状态转移方程:dp[ j+num[i] ]+=dp[j]
一共进行11次这样的动态规划即可求解
这样做可以避免重复,是因为我们算组合数时,从小到大每次都只多考虑一种面值的硬币,因此不会重复
另外,有一个初始化的位置很重要,写在代码注释中了
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 5 using namespace std; 6 7 const int num[11]={2000,1000,400,200,100,40,20,10,4,2,1}; 8 long long dp[6050]; 9 10 int main() 11 { 12 double _d; 13 14 while(scanf("%lf",&_d)==1) 15 { 16 int d=_d*100+0.5; 17 d/=5; 18 if(d==0) 19 break; 20 21 memset(dp,0,sizeof(dp)); 22 23 dp[0]=1;//这个初始化很重要,这样在下面循环中,每次j=0时,就是dp[num[i]]+=1,即要算num[i]这么大面值的组合方法时加上只用num[i]这么大面值的一个硬币的情况 24 25 for(int i=10;i>=0;i--) 26 for(int j=0;j+num[i]<=d;j++) 27 dp[j+num[i]]+=dp[j]; 28 29 printf(" %6.2f%17lld ",_d,dp[d]); 30 } 31 32 return 0; 33 }