HDU2069-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, 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

分析:

题意:
有1块、5块、10块、25块和50块的硬币无数,现在给出一个钱的数值,问用这几种硬币组成该值有多少种不同的组成方式?要求:硬币的个数不能超过100个,而且钱的数值不会超过250)

分析:
做题做到这里,因为这是DP专题,所以因该是用DP算法,我还特意去看了DD大牛的背包九讲,分析得出,这是二维费用背包!网上有人说这是完全背包,但我觉得是二维费用背包!一千个读者就有一千个哈姆雷特嘛!有5种物品,物品的个数限制为100,体积分别是1、5、10、25、50.现在有一个体积为n的背包,问装满这个背包有多少种方式?

状态转移方程:

for(i:1~5)//物品种类
{
	for(num:0~100)//物品个数
	{
		for(v:0~n)//背包体积
		{
			dp[j][num]+=dp[j-a[i]][num-1];//在体积为j的背包里装入num个物品的方法数可以由在剩余容量为j-a[i]的装有num-1个物品的背包里装入一个体积为a[i]的物品
		}
	}
}

代码:

#include<iostream>
#include<cstdio>
#define N 5

using namespace std;

int price[N]={1,5,10,25,50};
long long dp[101][255];

int main()
{
	int n;
	dp[0][0]=1;
	for(int i=0;i<5;i++)
	{
		for(int k=1;k<=100;k++)
		{
			for(int j=price[i];j<=250;j++)
			{
				dp[k][j]+=dp[k-1][j-price[i]];
			}
		}
	}
	while(~scanf("%d",&n))
	{
		long long num=0;
		for(int i=0;i<=100;i++)
		{
			num+=dp[i][n];
		}
		printf("%lld\n",num);
	}
	return 0;
 } 
发布了46 篇原创文章 · 获赞 16 · 访问量 395

猜你喜欢

转载自blog.csdn.net/weixin_43357583/article/details/105152251