赞
踩
题目:
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
这是一道经典的动态规划问题,重点是状态转移方程的理解。面值从小到达排序如下5c,10c,20c,50c,$1,$2,$5,$10,$20,$50,$100。考虑r[i][j]的意义是只用前i种硬币凑出j美元的方法数。所以r[1][j]明显就是1,因为只用5c,只会有一种方法。接着在这个基础上再加入第二种硬币10c,所以r[2][j]应该是在r[1][j]的基础上加上r[2][j-10c](此处表述有问题,但是方便理解),例如r[2][20] = r[1][20] + r[2][10],这里要注意是r[2][10],而不是r[1][10]。因为加入10c这种硬币后r[1][10]发生了更新,应该是加上更新后的值。加上r[2][10]的原因是r[2][10]可通过r[1][10]加上一个10c硬币得到。
所以状态转换方程是:r[i][j] = r[i - 1][j] + r[i][j - c[i]]
要注意一点时j> =c[i],这也很好理解,如果j<=c[i],加入硬币c[i]也不关c[i][j]的事
还有一种更为简单的状态转移方程是:r[i] += r[i-c[j]],理解思路是一样的。
AC代码如下:
#include<stdio.h>
#include<string.h>
#define maxn 6001
long long r[12][maxn];
const int c[12] = { -1,1,2,4,10,20,40,100,200,400,1000,2000 };
int main()
{
double n;
int i, j;
memset(r[0], 0, sizeof(r[0]));
for (i = 1; i<12; i++) {
r[i][0] = 1;
for (j = 1; j<maxn; j++) {
if (j >= c[i]) r[i][j] = r[i - 1][j] + r[i][j - c[i]];
else
r[i][j] = r[i - 1][j];
}
}
while (~scanf("%lf", &n) && n != 0.00) {
int a = int(n * 100 + 0.5);
printf("%6.2f%17lld\n", n, r[11][a / 5]);
}
return 0;
}
说明此题不用long long会溢出,VC++6.0下用long long会报错。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。