问题 G: 找零钱

本文介绍了一个简单的找零算法,该算法使用队列和结构体来找出给定金额下最少的纸币数量组合。通过处理不同面额的纸币,算法能够高效地给出最优解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题 G: 找零钱
时间限制: 1 Sec 内存限制: 128 MB
献花: 36 解决: 36
[献花][花圈][TK题库]
题目描述
小智去超市买东西,买了不超过一百块的东西。收银员想尽量用少的纸币来找钱。
纸币面额分为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

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <algorithm>
#include <queue>
using namespace std;

typedef struct
{
    int M;
    int c;
}relation;

int main()
{
#ifdef _DEBUG
    //freopen("data.txt", "r+", stdin);
    fstream cin("data.txt");
#endif // _DEBUG

    int M, LM[] = { 50,20,10,5,1 };
    queue<relation> que; relation tmp;
    while (cin >> M)
    {
        int i = 0;
        while (M > 0)
        {
            int n = 0;
            while (M - LM[i] >= 0)
            {
                ++n;
                M -= LM[i];
            }
            if (n)
            {
                tmp.M = LM[i]; tmp.c = n;
                que.push(tmp);
            }
            ++i;
        }
        while (!que.empty())
        {
            tmp = que.front();
            que.pop();
            cout << tmp.M << "*" << tmp.c;
            if (!que.empty())
                cout << "+";
        }
        cout << endl;
    }

#ifdef _DEBUG
    cin.close();
#ifndef _CODEBLOCKS
    system("pause");
#endif // !_CODEBLOCKS
#endif // _DEBUG

    return 0;
}

/**************************************************************
    Problem: 5038
    User: Sharwen
    Language: C++
    Result: 升仙
    Time:0 ms
    Memory:1712 kb
****************************************************************/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值