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;
}