问题 G: 找零钱
时间限制: 1 Sec 内存限制: 128 MB
题目描述
小智去超市买东西,买了不超过一百块的东西。收银员想尽量用少的纸币来找钱。
纸币面额分为50 20 10 5 1 五种。请在知道要找多少钱n给小明的情况下,输出纸币数量最少的方案。 1<=n<=99;
输入
有多组数据 1<=n<=99;
输出
对于每种数量不为0的纸币,输出他们的面值*数量,再加起来输出
~~
样例输入
~~
25
32
样例输出
201+51
201+101+1*2
经验总结
一定要见多识广!
AC代码
#include <cstdio>
#include <algorithm>
using namespace std;
struct money
{
int value;
int count;
};
bool cmp(money a, money b)
{
if(a.count != 0 && b.count == 0)
return true;
else if(a.count == 0 && b.count != 0)
return false;
else if(a.count != 0 && b.count != 0)
return a.value > b.value;
else
return true;
}
int main()
{
int n;
while (scanf("%d", &n) != EOF)
{
money mon[5] = {{50, 0}, { 20, 0}, {10, 0}, {5, 0}, {1, 0}};
for(int i = 0; i < 5; i++)
{
if(n >= mon[i].value)
{
mon[i].count = n / mon[i].value;
n %= mon[i].value;
}
}
sort(mon, mon + 5, cmp);
for(int i = 0; i < 5; i++)
{
if(mon[i].count != 0)
{
printf("%d*%d", mon[i].value, mon[i].count);
if(mon[i + 1].count != 0 && i + 1 <5)
printf("+");
}
}
printf("\n");
}
return 0;
}
本文介绍了一种找零钱算法,旨在使用最少数量的纸币完成找零。通过定义不同面额的纸币并采用贪心算法,文章详细解释了如何针对特定金额找到最优的找零方案,并附带了实现这一算法的C++代码。
646

被折叠的 条评论
为什么被折叠?



