【算法笔记4.4小节-贪心】问题 G: 找零钱

版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/xunalove/article/details/87967233

题目链接:http://codeup.cn/problem.php?cid=100000584&pid=6

题目描述

小智去超市买东西,买了不超过一百块的东西。收银员想尽量用少的纸币来找钱。
纸币面额分为50 20 10 5 1 五种。请在知道要找多少钱n给小明的情况下,输出纸币数量最少的方案。 1<=n<=99;

输入

有多组数据  1<=n<=99;

输出

对于每种数量不为0的纸币,输出他们的面值*数量,再加起来输出

样例输入

25
32

样例输出

20*1+5*1
20*1+10*1+1*2

每次取面值最大的数,直到取不了,再取下一个面值的纸币。


#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct Money{
    int num=0;
    int m=0;
};
int main()
{
    int n;
    while(scanf("%d",&n),n!=0)
    {
        Money a[5];
        a[0].m = 50;
        a[1].m = 20;
        a[2].m = 10;
        a[3].m = 5;
        a[4].m = 1;
        while(n>=50)
        {
            n-=50;
            a[0].num++;
        }
        while(n>=20)
        {
            n-=20;
            a[1].num++;
        }
        while(n>=10)
        {
            n-=10;
            a[2].num++;
        }
        while(n>=5)
        {
            n-=5;
            a[3].num++;
        }
        a[4].num = n;
        n=0;
        Money ans[5];
        int k=0;
        for(int i=0; i<5; i++)
        {
            if(a[i].num>0)
            {
                ans[k++] =a[i];
            }
        }
        for(int i=0; i<k; i++)
        {
            printf("%d*%d",ans[i].m, ans[i].num);
            if(i<k-1)
                printf("+");
            else
                printf("\n");
        }

    }
}

猜你喜欢

转载自blog.csdn.net/xunalove/article/details/87967233
今日推荐