钱币找零问题-贪心算法解析

cpp 复制代码
#include <iostream> 

using namespace std;

#define N  7 

int counts[N] = { 3, 2, 0, 3 ,2 ,0 , 1 };
int value[N] = { 1, 2, 5, 10, 20, 50, 100 }; 
int cot[N] = { 0, 0, 0, 0 ,0 ,0 , 0 };

int solve(int money) {
	int num = 0; //支付了几张纸币
	int i = 0;

	for (i = N - 1; i >= 0; i--) {
		int j = money / value[i]; //对应的纸币要给几张
		//有这么多给对应的钱,没有那些有多少给多少
		int c = j > counts[i] ? counts[i] : j; 

		cout << "需要面值" << value[i] << "的纸币" << c << "张" << endl;
		money -= c * value[i]; //还剩多少要给
		num += c; 

		if (money == 0) { break; }
	}
	if (money > 0) { num = -1; } //不能完全支付

	return num;
}

int main() {
	int money = 0;
	int num = 0;

	cout << "请输入要支付的数目:\n";
	cin >> money;

	num = solve(money);

	if (num == -1) {
		cout << "支付失败!" << endl;
	}
	else {
		cout << "成功支付款项:" << num << endl;
	}

	system("pause");
	return 0;
}
相关推荐
闲人不梦卿6 小时前
数据结构之排序方法
数据结构·算法·排序算法
TracyCoder1236 小时前
LeetCode Hot100(24/100)——21. 合并两个有序链表
算法·leetcode·链表
power 雀儿6 小时前
前馈网络+层归一化
人工智能·算法
爱吃rabbit的mq6 小时前
第10章:支持向量机:找到最佳边界
算法·机器学习·支持向量机
木非哲6 小时前
AB实验高级必修课(四):逻辑回归的“马甲”、AUC的概率本质与阈值博弈
算法·机器学习·逻辑回归·abtest
CSDN_RTKLIB6 小时前
CMake制作动态库与静态库对比
c++
wWYy.6 小时前
C++—集群聊天室(3)CMake详解
开发语言·c++
在路上看风景6 小时前
16. 指针和引用的区别
c++
兩尛6 小时前
45. 跳跃游戏 II
c++·算法·游戏
睡一觉就好了。6 小时前
C++ 容器
开发语言·c++