Coin Changing Problem(01背包)
题目
Find the minimum number of coins to make change for n cents using coins of denominations d1, d2,…, dm.
The coins can be used any number of times.
输入
Two integers n and m are given in the first line.
The available denominations are given in the second line.
输出
Print the minimum number of coins in a line.
数据范围
1 ≤ n ≤ 50000
1 ≤ m ≤ 20
1 ≤ denomination ≤ 10000
The denominations are all different and contain 1.(各面值均不同,其中必须包含1)
样例输入1
55 4
1 5 10 50
样例输出1
2
样例输入2
15 6
1 2 7 8 12 50
样例输出2
2
样例输入3
65 6
1 2 7 8 12 50
样例输出3
3
题意
现有面值为C1,C2,…,Cm元的m种硬币,求支付n元时所需的最少硬币数。
各面值的硬币量不限使用。
思路
最近开始上手动态规划。
首先我们设定两个数组c与t:
int c[25]; //c[i]:第i个硬币的面值
int t[50050]; //t[j]:当支付数为j元时所需的硬币最少量
当支付额为 j 元时,t[j] 为不放 c[i] 总额达到 j 元的最少数量,t[j-c[i]]+1为取1枚c[i]总额达到 j 元的最少数量。
t[j]的值应为两者之间较小值。
此时我们就得到了这道题的状态转移方程:
t[j]=min(t[j],t[j-c[i]]+1);
然后补充一下代码就可以了。
「伊丽莎白」!
代码
#include<bits/stdc++.h>
using namespace std;
int c[25]; //c[i]:第i个硬币的面值
int t[50050]; //t[j]:当支付数为j元时所需的硬币最少量
int main()
{
int n,m;
while(cin>>n>>m)
{
for(int i=1;i<=m;i++)
cin>>c[i];
for(int i=1;i<=n;i++)
t[i]=1e9+7; //求最小值设置比较大的值,如果是求最大值就设小一点
t[0]=0;
for(int i=1;i<=m;i++)
for(int j=0;j+c[i]<=n;j++)
t[j+c[i]]=min(t[j+c[i]],t[j]+1); //状态转移方程
cout<<t[n]<<endl;
}
}
自己对于动态规划的理解还没有很深入,对于一些细节也不是很理解。
一些细节方面应该还会再改动。
我()懂()你()没()懂()。
针不戳~
下次再见!