题目:
有n种硬币,面值分别为V1,V2,…Vn,每种都有无限多。给定非负整数S,可以选用多少个硬币,使得面值之和恰好为S?输出硬币数目的最小值和最大值。1 <= n <= 100,0 <= S <= 100,1 <= Vi <= S。
分析:
将每种面值看作一个点,表示“需要凑足的面值”,本题的初始状态为S,目标状态为0。
最小值:用d(i) 表示从面值为 i 到面值为0使用的最少硬币数。则状态转移方程:d(i) = min{d(i-Vj)+1} ,其中1 <= j <= n。当i = 0时,显然d(i) = 0。 INT_MAX 表示最大整数,表示不可达,本程序采用自定义INF表示不可达。
最大值类似。
代码:
采用递推求最小值:
#include <cstdio>
#include <string.h>
#include <algorithm>
using namespace std;
const int maxn = 100 + 5;
const int maxS = 10000 + 5;
const int INF = 1<<30; // 不可达的数量
int V[maxn], // 面值数组
d