ArcTan

dfs
随笔 - 16, 文章 - 117, 评论 - 6, 引用 - 0
数据加载中……

白书上的动态规划D---dp组合计数问题

Coin Change 

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, two 5-cent coins and one 1-cent coin, 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 7489 cents.

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 

11 26 

Sample Output 

4 13 

题目大意:

 给定1 5 10 25 50五种硬币,给定一个数,问用这些硬币有多少种不同的组合方式?

想想好像可以是一个方程组求解的问题嘛:

                x1+5*x2+10*x3+25*x4+50*x5=x0;

                给定x0,一组满足条件的x>=0就是解集。啊哈哈哈。可以高斯消元法咯。

不过,明显的计数问题:

dp[i][j]表示i可以由前j种硬币表示的方法数。

dp[i][j]=dp[i][j-1]+dp[i-coin[j]][j]     i-coin[j]>0

dp[i][j]=dp[i][j-1]+1  i-coin[j]=0;

dp[i][j]=dp[i][j-1] i-coin[j]<0

总结:

      方程类问题,一定要先把方程写清楚!!!

#include<stdio.h>
#include<string.h>
#include<math.h>
long long dp
[7500][5],coin[5]={1,5,10,25,50};
int GetAns()
{
    int i
,j;
    memset(dp,0,sizeof(dp));
    dp[1][0]=dp[1][1]=dp[1][2]=dp[1][3]=dp[1][4]=1;
    for (i=2;i<=7489 ;i++ )
    {
        dp
[i][0]=1;
        for (j=1;j<5 ;j++ )
            if (i-coin[j]>0)
                dp
[i][j]=dp[i][j-1]+dp[i-coin[j]][j];
            else
                if (i-coin
[j]==0)
                    dp
[i][j]=dp[i][j-1]+1;
                else
                    dp
[i][j]=dp[i][j-1];
    }
}
int main()
{
    int n
;
    GetAns();
    while (scanf("%d",&n)==1)
        printf(
"%lld\n",dp[n][4]);
    return 0;
}


额额,dp是个好东西,该看看优化了!!!

posted on 2012-04-29 19:11 wangs 阅读(821) 评论(0)  编辑 收藏 引用 所属分类: ACM-DP


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理