贪婪算法

1.钱币找零问题
这个问题在我们的日常生活中就更加普遍了。假设1元、2元、5元、10元、20元、50元、100元的纸币分别有c0, c1, c2, c3, c4, c5, c6张。

现在要用这些钱来支付K元,至少要用多少张纸币?

用贪心算法的思想,很显然,每一步尽可能用面值大的纸币即可。在日常生活中我们自然而然也是这么做的。

在程序中已经事先将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\n", greedy_money(m));
    return 0;
}

 

posted @ 2019-04-23 16:08  小时候挺菜  阅读(528)  评论(0编辑  收藏  举报