The greedy algorithm solves the coin-seeking problem.
If a currency has a coin with a nominal value of 1 cent, 2 cent, 5 cent, and 1 cent, how many coins are needed to find the change with K cent?
According to the greedy algorithm, we need to constantly use coins with the largest face value. If the value to be zero is smaller than the largest coin value, try the second largest coin, and so on.
The Code is as follows:
# Include <iostream> using namespace std; # define ONE 1 # define TWO 2 # define FIVE 5 # define TEN 10int main () {int money; int one = 0, two = 0, five = 0, ten = 0; cout <"Enter the money (in units) for the Change:"; cin> money; // try every 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 result cout <"1 cent 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 does not obtain the overall optimal solution for all problems, many problems in practical application can use the greedy algorithm to obtain the optimal solution. Sometimes, even if the greedy algorithm cannot obtain the optimal solution, the final result is a better solution.