钱币找零C++

描述:

假设1元、2元、5元、10元、20元、50元、100元的纸币分别有c0, c1, c2, c3, c4, c5, c6张。现在要用这些钱来支付K元,至少要用多少张纸币?

代码:

具体数字视情况而定

#include<vector>
#include<iostream>
#include<algorithm>
using namespace std;

struct cmp
{
	bool operator()(vector<int>& array1, vector<int>& array2)
	{
		return array1[0] > array2[0];
	}
};

int solve(int money, const vector<pair<int, int>>& moneyCount)
{
	int num = 0;
	//首先选择最大面值的纸币
	for (int i = moneyCount.size() - 1; i >= 0; i--)
	{
		//需要的当前面值与面值数量取最小
		int c = min(money / moneyCount[i].first, moneyCount[i].second);
		money = money - c * moneyCount[i].first;
		num += c;
	}
	if (money > 0)
		num = -1;
	return num;
}
int main()
{
	//存放纸币与数量: first:纸币,second:数量
	vector<pair<int, int>> moneyCount = { { 1, 3 }, { 2, 1 }, { 5, 4 }, { 10, 3 }, { 20, 0},{50, 1}, { 100, 10 } };
	sort(moneyCount.begin(), moneyCount.end(), cmp());
	int money;
	cout << "请输入要支付的钱" << endl;
	cin >> money;
	int res = solve(money, moneyCount);
	if (res != -1)
		cout << res << endl;
	else
		cout << "NO" << endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值