In real life, we often encounter the problem of changing the value of 0. Suppose there are a number of unlimited coins with a nominal value of 20, 10, or 5.
The solution for finding the desired number of coins is provided. The minimum number of coins is required.
For this type of problem, the greedy algorithm always selects the maximum number of coins that can be used to find money. For example, if you want to find 25 yuan, you can find 20 + 5 instead of 10 + 10 + 5.
The following is the c language implementation (DEV c ++ 4.9.2 runs through)
[Cpp]
# Include <stdio. h>
Void greedyMoney (int m [], int k, int n );
Int main (void)
{
Int money [] = {20, 10, 5, 1 };
Int k;
K = sizeof (money)/sizeof (money [0]);
GreedyMoney (money, k, 25 );
System ("PAUSE ");
}
/*
* M []: stores the face values available for change in descending order.
* K: The number of nominal value types available for change.
* N: the number of zeros to be updated.
*/
Void greedyMoney (int m [], int k, int n)
{
Int I;
For (I = 0; I <k; I ++)
{
While (n> = m [I] & n> 0)
{
Printf ("% d.", m [I]);
N = n-m [I];
}
}
Printf ("\ n ");
}
# Include <stdio. h>
Void greedyMoney (int m [], int k, int n );
Int main (void)
{
Int money [] = {20, 10, 5, 1 };
Int k;
K = sizeof (money)/sizeof (money [0]);
GreedyMoney (money, k, 25 );
System ("PAUSE ");
}
/*
* M []: stores the face values available for change in descending order.
* K: The number of nominal value types available for change.
* N: the number of zeros to be updated.
*/
Void greedyMoney (int m [], int k, int n)
{
Int I;
For (I = 0; I <k; I ++)
{
While (n> = m [I] & n> 0)
{
Printf ("% d.", m [I]);
N = n-m [I];
}
}
Printf ("\ n ");
}
It should be noted that, in some cases, the greedy algorithm cannot obtain the overall optimal solution, but the result may be a good approximation of the optimal solution.
For example, if the value of 0 is, 5, 1, and 15.
Use the greedy algorithm to find 0: 11 + 1 + 1 + 1 + 1. Five coins are required.
The optimal solution is 5 + 5 + 5, and only three coins are needed.