http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=83
147 - Dollars
Time limit: 3.000 seconds
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
分析:
这个题跟UVA674题类似,只是这个题有更多的钱的种类,并且需要用long long来保存
做的方法是先乘以100消除浮点数的误差,然后计算,需要注意的是输出格式有要求,有特殊的空格要求~
AC代码:
递推:
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
const int maxn=;
int num[]={,,,,,,,,,,,};
int a,b;
long long f[maxn][];
void Init()
{
for(int i=;i<;i++)
f[][i]=;
for(int i=;i<maxn;i++)
for(int j=;j<;j++)
for(int k=;num[j]*k<=i;k++)
f[i][j]+=f[i-num[j]*k][j-];
}
int main()
{
Init();
while(scanf("%d.%d",&a,&b)&&(a+b))
{
int n=a*+b;
printf("%6.2lf%17lld\n",n*1.0/,f[n][]);
}
return ;
}
背包:
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
const int maxn=;
int num[]={,,,,,,,,,,,};
int a,b;
long long f[maxn][];
void Init()
{
for(int i=;i<;i++)
f[][i]=;
for(int i=;i<maxn;i++)
for(int j=;j<;j++)
for(int k=;num[j]*k<=i;k++)
f[i][j]+=f[i-num[j]*k][j-];
}
int main()
{
Init();
while(scanf("%d.%d",&a,&b)&&(a+b))
{
int n=a*+b;
printf("%6.2lf%17lld\n",n*1.0/,f[n][]);
}
return ;
}
后来想到可以再除以5(题目说是5的倍数),来减少运算量,提高运算效率。
#include <cstdio>
using namespace std; long long f[];
const int num[] = {, , , , , , , , , , }; int main()
{
f[] = ;
for(int i = ;i <= ;i ++)
for(int j = num[i] ;j <= ;j ++)
f[j] += f[j - num[i]];
double x;
while(scanf("%lf", &x) , x)
{
double tx = x * ;
printf("%6.2lf%17lld\n", x , f[(int)tx] );
}
return ;
}