Coin Changing Problem Aizu - DPL_1_A 基础DP

本文介绍了一个经典的动态规划问题——找零问题,即如何使用最少数量的硬币组合来构成给定金额。该文提供了完整的C++代码实现,并通过实例展示了算法的工作原理。

Find the minimum number of coins to make change for n cents using coins of denominations d1d2,.., dm. The coins can be used any number of times.

Input

n m
d1 d2 ... d

m

Two integers n and m are given in the first line. The available denominations are given in the second line.

Output

Print the minimum number of coins in a line.

Constraints

  • 1 ≤ n ≤ 50000
  • 1 ≤ m ≤ 20
  • 1 ≤ denomination ≤ 10000
  • The denominations are all different and contain 1.

Sample Input 1

55 4
1 5 10 50

Sample Output 1

2

 

Sample Input 2

15 6
1 2 7 8 12 50

Sample Output 2

2

 

Sample Input 3

65 6
1 2 7 8 12 50

Sample Output 3

3
 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 #define read(x) scanf("%lld",&x)
 4 #define out(x) printf("%lld",&x)
 5 #define cfread(x) scanf("%I64d",&x)
 6 #define cfout(x) printf("%I64d",&x)
 7 #define mian main
 8 #define min(x,y) (x<y?x:y)
 9 #define max(x,y) (x<y?y:x)
10 #define f(i,p,q,t) for(i=p;i<q;i+=t)
11 #define MAXN 110000
12 #define inf 0x3f3f3f3f
13 #define mem(x,t) memset(x,t,sizeof(x));
14 #define T true
15 #define F false
16 #define def -1*inf
17 typedef long long ll;
18 typedef long long LL;
19 typedef double dd;
20 const ll maxn = 110000;
21 int f[maxn];
22 int a[maxn];
23 int main(){
24     int n,m;
25     scanf("%d%d",&n,&m);
26     for(int i=1;i<=m;i++)
27         scanf("%d",&a[i]);
28     memset(f,-1,sizeof(f));
29     f[0] = 0;
30     for(int i = 1;i<=m;i++){
31         for(int j=a[i];j<=n;j++){
32             if(f[j]==-1&&f[j-a[i]]!=-1)
33                 f[j]=f[j-a[i]]+1;
34             f[j] = min(f[j],f[j-a[i]]+1);
35         }
36     }
37     printf("%d\n",f[n]);
38     return 0;
39 }

 

转载于:https://www.cnblogs.com/xfww/p/8696641.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值