您的位置:首页 > 其它

【背包/母函数】HDU2069-Coin Change

2016-08-15 16:17 369 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2069

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

 

Sample Output

4
13

母函数代码:

#include<iostream>
#include<cstring>
using namespace std;
const int maxn=251;
int n;
//  这里要注意,有个限制,总硬币个数不超过100个;所以我们要使用二维数组保存,
//  这第二维我们用来保存硬币总个数
int f[maxn][maxn]={0};
int tmp[maxn][maxn]={0};
int a[6]={0,1,5,10,25,50};
void faction()
{
//for(int i=0;i<=100;i++)     //  1分硬币拼成值为i的必须用i个硬币
//    f[i][i]=1;
f[0][0]=1;
for(int i=1;i<=5;i++){          //  表达式个数
for(int j=0;j<maxn;j++){   //  第一个表达式的因子枚举
for(int k=0;k+j<maxn;k+=a[i]){   //  第二个表达式;所提供的指数;
for(int l=0;l+k/a[i]<=100;l++){
tmp[j+k][l+k/a[i]]+=f[j][l];
}
}
}
for(int j=0;j<maxn;j++){
for(int l=0;l<=100;l++){
f[j][l]=tmp[j][l];
tmp[j][l]=0;
}
}
}
for(int i=0;i<maxn;i++){
for(int j=0;j<=100;j++){
f[i][101]+=f[i][j];
}
}
}
int main()
{
int n;
faction();
cin.sync_with_stdio(false);
while(cin>>n){
cout<<f
[101]<<endl;
}
return 0;
}


背包代码:
#include<iostream>
using namespace std;
const int maxn=251;
int dp[maxn][maxn]={0};
int a[6]={1,5,10,25,50};
void ZeroOnePack()
{
dp[0][0]=1;
for(int i=0;i<5;i++){ // 枚举硬币种类;
for(int j=1;j<=100;j++){ // 限制硬币个数;
for(int k=a[i];k<maxn;k++){ // 构成的价值;
dp[j][k]+=dp[j-1][k-a[i]];
}
}
}
for(int i=0;i<maxn;i++){
for(int j=0;j<=100;j++){
dp[101][i]+=dp[j][i];
}
}
}
int main()
{
int n;
ZeroOnePack();
cin.sync_with_stdio(false);
while(cin>>n){
cout<<dp[101]
<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: