HDU 2069 & UVA 674 Coin Change(换硬币 dp 入门经典水题,背包问题)

 

Coin Change

Time Limit: 1000MS Memory Limit: 32768KB 64bit IO Format: %I64d & %I64u

 

 

 

 

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

 

Sample Output

 

4 13

 

 

 

 

题意;

一共有 n 元钱,现在有  1 、5、10、25、50 元的钱,问你有多少种方式组合成 n 元钱!

 

换硬币,动态规划入门经典题型,没有看过《背包九讲》的可以看看《背包九讲》,所以我在这里也就不多说了,状态转移方程   dp[j] = dp[j] + dp[ j - a[i] ];

 

附上《背包九讲》链接 :http://blog.youkuaiyun.com/xia842655187/article/details/51334431 点击打开链接

之前由于做得是 UVA 674,以为HDU 2069也是一样的,没太注意看,对之前看博客的朋友说声抱歉!!!谢谢各位朋友的提示!现将 HDU 2069 的代码补上!

HDU 2069题目最后有个限制条件:Your program should be able to handle up to 100 coins. 
意思是:最多只能有100个硬币

附上  HDU 2069代码(UVA 674 代码见后面):

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
const int a[5]={1,5,10,25,50};
long long dp[255][101];
int main()
{
    int n;
    while(cin>>n){
        memset(dp,0,sizeof(dp));
        dp[0][0]=1;
        for(int i=0;i<5;i++){
            for(int k=1;k<=100;k++){//k个硬币
                for(int j=a[i];j<=n;j++){
                    dp[j][k]+=dp[j-a[i]][k-1];
                }
            }
        }
        int res=0;
        for(int i=0;i<=100;i++){
            res+=dp[n][i];
        }
        cout<<res<<endl;
    }
	return 0;
}

附上 UVA 674代码:

 

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#define INF 0x3f3f3f3f
using namespace std;

int main()
{
	int n;
	while(cin >> n)
	{
		int a[5] = {1,5,10,25,50};
		long long int dp[8000] = {0};         //  需要用到  long long 结果有可能超出 int 范围
		dp[0] = 1;
		for(int i = 0;i < 5;i++)
		{
			for(int j = a[i];j <= n;j++)
			{
				dp[j] = dp[j] +dp[j - a[i]];
			}
		}
		cout << dp[n] << endl;
	}
	return 0;
}

 

 

 

 

 

 

 

 

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值