- 描述:
- Poor Bessie has taken a job in the convenience store located just over the border in Slobbovia. Slobbovians use different coinages than the USA; their coin values change day-by-day!
- Help Bessie make optimal change for Slobbovian shoppers. You will need to create C (1 <= C <= 1000) cents of change using N (1 <= N <= 10) coins of various values. All test cases will be solvable using the supplied coins.
- If 5 coins of values 50, 25, 10, 5, and 1 were available, Bessie would make optimum change (minimal coins) of 93 cents by using 1 x 50, 1 x 25, 1 x 10, 1 x 5, and 3 x 1 coins (a total of 7 coins).
- How hard could it be? The final two test cases will be challenging.
- 输入:
- Line 1: Two space-separate integers: C and N
- Lines 2..N+1: Each line contains a single unique integer that is a coin value that can be used to create change
- 输出:
- Line 1: A single integer that is the minimum number of coins to create C cents
- 输入样例:
- 93 5
- 25
- 50
- 10
- 1
- 5
- 输出样例:7
- 解题思路:先想到用贪心法,可以从大的面额开始算,直到超出,然后换成小的面额去求,直到求出一个N,但后来总觉得有个地方可能会做不到,没那么容易贪的,如果面额没有1的时候,是不是可能出现不能刚好的情况, 这个时候就得反过来让大的面额进行减少的处理,有点小麻烦。就想用另一种方法,动态规划,比如既然要求面额为93的最优解,就得求出92、91、90一直到1的最优解,把问题一直小化处理
- 例如:面值为50、25、1、10、5 求93的最优解
- 要求93得先求43、68、92、83、88的最优解+1,就这样一直求下去
- 时间复杂度:O(m*n);
- 代码如下:
- #include<iostream>
- using namespace std ;
- int main()
- {
- int n,m;
- int a[500]={0};
- int b[10000]={0};
- cout<<"请输入硬币面值的个数:";
- cin>>n;
- cout<<"请输入各个硬币的面值:";
- for(int i=1;i<=n;i++)
- cin>>a[i];
- cout<<"请输入要找的钱:";
- cin>>m;
- void coin(int n , int m , int a[] , int b[]) ;
- coin(n , m , a , b) ;
- cout << "最优解为:" << b[m] << endl ;
- return 0;
- }
- void coin(int n , int m , int a[] , int b[])
- {
- b[0] = 0 ;
- for(int i=1 ; i<=m ; i++)
- {
- int min = m ;
- for(int j=1 ; j<=n ; j++)
- {
- if(i>=a[j] && b[i-a[j]] < min)
- min = b[i-a[j]] ;
- }
- b[i] = min + 1 ;
- }
- }