If there is a currency, it has 1 cents, 2 points, 5 points and 1 corners of the coin, at least how many coins to find the K-penny change?
According to the idea of greedy algorithm, it is necessary to use the coin with the most face value constantly. If the value of change is less than the maximum coin value, try the second largest coin, and so on.
The code is as follows:
#include <iostream>using namespace std; #define One 1#define, 2#define FIVE 5#define TEN 10int Main () { int mon EY; int one=0,two=0,five=0,ten=0; cout<< "Enter the money for change (to be divided into units):"; cin>>money; Try each kind of coin while (Money>=ten) { ten++; Money-=ten; } while (money>=five) { five++; money-=five; } while (Money>=two) { two++; money-=two; } while (Money>=one) { one++; Money-=one; } Output cout<< "1 Corner coin Count:" <<ten<<endl; cout<< "5 cent coin Count:" <<five<<endl; cout<< "2 cent coin Count:" <<two<<endl; cout<< "1 cent coin Count:" <<one<<endl; return 0;}
Although the greedy algorithm is not able to get the overall optimal solution for all problems, many problems in practical application can be obtained by using greedy algorithm to obtain the optimal solution. Sometimes the optimal solution of the problem can not be obtained even though the greedy algorithm is used, but the final result is also a better solution
Greedy algorithm to solve coin change problem