贪婪算法
1.錢幣找零問題
這個(gè)問題在我們的日常生活中就更加普遍了。假設(shè)1元、2元、5元、10元、20元、50元、100元的紙幣分別有c0, c1, c2, c3, c4, c5, c6張。
現(xiàn)在要用這些錢來支付K元,至少要用多少張紙幣?
用貪心算法的思想,很顯然,每一步盡可能用面值大的紙幣即可。在日常生活中我們自然而然也是這么做的。
在程序中已經(jīng)事先將Value按照從小到大的順序排好。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int count[] = {3, 0, 2, 1, 0, 3, 5};
int value[] = {1, 2, 5, 10, 20, 50, 100};
int min(int a, int b)
{
return a > b ? b : a;
}
int greedy_money(int money)
{
int i, j;
j = 0;
for (i = 6; i >= 0 ; i--)
{
if(money/value[i] > 0)
{
int n = min((int)money/value[i], count[i]);
money = money - n * value[i];
j = j + n;
if (money <= 0)
{
break;
}
}
}
if(money > 0)
{
return -1;
}
return j;
}
int main()
{
int m;
scanf("%d", &m);
printf("%d
", greedy_money(m));
return 0;
}
總結(jié)
- 上一篇: 《设计师要懂心理学》-第四章-人如何思考
- 下一篇: 十分钟教你永久打开完整版Google P