UVA 357 Let Me Count The Ways(完全背包)

题目概括:

一共有1、5、10、25、50五种面值的钱币,输入多组金额,分别求出用这五种钱币一共有多少种组合方式。

题目解析:

该题目涉及了完全背包的算法。

有两个博客对于这个算法有详细的解释,在这里引用一下:
https://blog.csdn.net/qq_38984851/article/details/81133840
https://www.cnblogs.com/fengziwei/p/7750849.html

代码:

#include<iostream>
using namespace std;   
const int MAXN=30000;
int coin[5]={1,5,10,25,50};   
long long f[MAXN+1];//f[i]表示i cents时的不同硬币组合数 
void complete(int n) //计算[1,n]之间的每种零钱组合
{   
int k,i;   
f[0]=1;// There is only 1 way to produce 0 cents change.   
for(k=0; k<5; k++)
    {       
         for(i=coin[k]; i<=n; i++)       
              {           
                    f[i]+=f[i-coin[k]];         
              }
    }
}

int main()  
{   
int n;   
complete(MAXN);   
while(cin>>n)
    {       
        if(f[n]==1)           
          cout<<"There is only 1 way to produce"<<n<<" cents change.\n";       
        else           
           cout<<"There are "<<f[n]<<" ways to produce "<<n<<" cents change.\n";
    }
return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44918971/article/details/89367573