最少硬币问题

我就是我 2022-02-16 01:57 344阅读 0赞

最少硬币问题

Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description

设有n种不同面值的硬币,各硬币的面值存于数组T[1:n]中。现要用这些面值的硬币来找钱。可以使用的各种面值的硬币个数存于数组Coins[1:n]中。
对任意钱数0≤m≤20001,设计一个用最少硬币找钱m的方法。
对于给定的1≤n≤10,硬币面值数组T和可以使用的各种面值的硬币个数数组Coins,以及钱数m,0≤m≤20001,计算找钱m的最少硬币数。

Input

输入数据第一行中只有1个整数给出n的值,第2行起每行2个数,分别是T[j]和Coins[j]。最后1行是要找的钱数m。

Output

输出数据只有一个整数,表示计算出的最少硬币数。问题无解时输出-1。

Sample Input

  1. 3
  2. 1 3
  3. 2 3
  4. 5 3
  5. 18

Sample Output

  1. 5
  2. #include <iostream>
  3. #include <math.h>
  4. #include <vector>
  5. using namespace std;
  6. int min(int a, int b) {
  7. return a < b ? a : b;
  8. }
  9. int main() {
  10. int n;
  11. int summoney;
  12. cin >> n;
  13. vector<int> t;
  14. vector<int> coin;
  15. int t1, coin1;//t 面值 coin 个数
  16. //方便起见 不用第0个元素存数据
  17. t.push_back(0);
  18. coin.push_back(0);
  19. for (int i = 1; i <= n; i++) {
  20. cin >> t1 >> coin1;
  21. t.push_back(t1);
  22. coin.push_back(coin1);
  23. }
  24. cin >> summoney;
  25. int dp[20005] = { 0 }; //dp[i] 用来记录钱数为i时的最少的硬币数
  26. for (int i = 1; i <= summoney; i++) {
  27. dp[i] = 99999;
  28. }
  29. for (int i = 1; i <= n; i++) {
  30. for (int j = 1; j <= coin[i]; j++) {//此处就表示如果再用一个面值为t[i]的硬币还能不能找零
  31. for (int k = summoney; k >= t[i]; k--) {
  32. dp[k] = min(dp[k - t[i]]+1, dp[k]);
  33. //cout << k << ": " << dp[k] << endl;
  34. }
  35. }
  36. }
  37. if (dp[summoney] == 99999) {
  38. cout << "-1" << endl;
  39. }
  40. else {
  41. cout << dp[summoney] << endl;
  42. }
  43. return 0;
  44. }

发表评论

表情:
评论列表 (有 0 条评论,344人围观)

还没有评论,来说两句吧...

相关阅读

    相关 硬币问题

    / 给出k中面值的硬币,每种硬币的数量无限,再给一个总金额amount,问最少需要几枚硬币凑出这个金额,如果凑不出,返回-1 dp[i]定义:当目标金额为i时,至少