• 所有硬币组合问题——动态规划hdu2069


    Problem Description
    Suppose there are 5 types of coins: 50-cent, 25-cent, 10-cent, 5-cent, and 1-cent. We want to make changes with these coins for a given amount of money.

    For example, if we have 11 cents, then we can make changes with one 10-cent coin and one 1-cent coin, or two 5-cent coins and one 1-cent coin, or one 5-cent coin and six 1-cent coins, or eleven 1-cent coins. So there are four ways of making changes for 11 cents with the above coins. Note that we count that there is one way of making change for zero cent.

    Write a program to find the total number of different ways of making changes for any amount of money in cents. Your program should be able to handle up to 100 coins.
     
    Input
    The input file contains any number of lines, each one consisting of a number ( ≤250 ) 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
    11 26
     
    现附上AC代码:

    #include<iostream>
    using namespace std;
    const int money=251;
    const int coin=101;
    int dp[money][coin]={0}; //dp[i][j]表示金额为i,硬币数为j的种类方法
    int value[5]={1,5,10,25,50};

    void solve()
    {
    //for(int i=0;i<money;i++) 这里为什么只能dp[0][0]=0,是因为dp[j][1]=dp[j][1]+dp[j-value[i]][k-1],只有j-value[i]==0时,才能在加1
    //dp[i][0]=1;
    dp[0][0]=1;
    for(int i=0;i<5;i++)
    {
    for(int j=value[i];j<money;j++)
    {
    for(int k=1;k<coin;k++)
    {
    dp[j][k]=dp[j][k]+dp[j-value[i]][k-1];
    }
    }
    }
    }
    int main()
    {
    solve();
    int ans[money]={0};
    ans[0]=1; //注意这一步,一定不能忘,一个特殊值
    for(int i=1;i<money;i++)
    {
    for(int j=1;j<coin;j++)
    {
    ans[i]=dp[i][j]+ans[i];
    }
    }
    int s;
    while(cin>>s)
    cout<<ans[s]<<endl;
    return 0;
    }

    因为刚开始学习动态规划,这种硬币问题算是入门的问题。到现在为止,我所理解的动态规划是利用递推关系式,对于某个解值是需要用之前的算出来的进行求解,也就是类似于我要想知道第三个值的数,就需要让第一个数乘以第二个数,举个例子,就像我们都熟知的斐波那契数列,但要注意初始值一定要弄明白,否则递推关系式将进行不下去。另外斐波那契数列是最简单的dp,稍微复杂一点的需要进行不止一次地递推,就像这次的硬币问题,需要递推5次。


    作者:孙建钊
    出处:http://www.cnblogs.com/sunjianzhao/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

  • 相关阅读:
    框架和库的区别
    象棋中常用的最小值最大值算法及剪枝算法
    cocos2dx 3.x中的渲染机制
    用vs2013编译lua源码方法
    VS中设置#define _CRT_SECURE_NO_WARNINGS的两种方式
    lua编程基础
    VS2013中如何更改主题颜色(深色)和恢复默认的窗口布局
    (二)识别NAND Flash Nor Flash
    Linux设备驱动之Ioctl控制
    linux驱动程序中的并发控制
  • 原文地址:https://www.cnblogs.com/sunjianzhao/p/11371647.html
Copyright © 2020-2023  润新知