Coin Change(UVA 674)

来源:互联网 发布:阿里云代码托管 收费 编辑:程序博客网 时间:2024/06/03 14:55

题目翻译:

有五种类型的硬币,面值分别为1分,5分,10分,25分,50分。现在你有n分钱,需要换为这五种硬币,请问最多有多少种换法。输入最多有7489 分钱。

Input 

The input file contains any number of lines, each one consisting of a number for the amount of money in cents.

Output 

For each input line, output a line containing the number of different ways of making changes with the above 5 types of coins.

Sample Input 

1126

Sample Output 

413

题解:

设计到状态变化,用动态规划求解。而每一个硬币面值为一个状态量。

状态方程为 dp[i] = dp[i] + dp[i - coin[k]];从上往下分析,形成了一颗五叉树。

思路:每添加一个硬币面值,不影响以前存在的硬币面值产生的结果,而是在此条件下新加了一些结果,符合叠加性原理。(做题的时候需要思考每个变量直接的因果关系)

代码:

#include<cstdio>#include<cstring>#include<cmath>#include<algorithm>#include<iostream>using namespace std;#define maxn 7500int d[maxn];void Init(){    d[0]=1;    const int coin[5]={1,5,10,25,50};    for(int k=0;k<5;k++){        for(int i=coin[k];i<maxn;i++){            d[i]+=d[i-coin[k]];        }    }}int main(){    int n;    Init();    while(scanf("%d",&n)!=EOF){        cout<<d[n]<<endl;    }    return 0;}


0 0
原创粉丝点击