初探贪心算法 -- 使用最少纸币组成指定金额

python实现:

# 对于任意钱数,求最少张数

n = int(input("money: "))   # 输入钱数
bills = [100, 50, 20, 10, 5, 2, 1]      # 纸币面额种类
total = 0
for b in bills:
    count = n // b  # 整除面额求用的纸币张数
    if count > 0:
        print(f"{b}纸币 张数{count}")
    n -= count * b		# 更新剩余金额
    total += count		# 累加纸币数量
print(f"总共用{total}张纸币")

运行结果:

money: 231
100纸币 张数2
20纸币 张数1
10纸币 张数1
1纸币 张数1
总共用5张纸币

c++实现:

#include 
using namespace std;

int calc(int n) {
    int count = 0;
    int total = 0;
    int b[6] = {100, 50, 10, 5, 2, 1};
    for (int i = 0; i < 6; i++) {
        count = n / b[i];
        if (count > 0) {
            total += count;
            cout << "面额" << b[i] << " " << "张数" << count << endl;
            n -= count * b[i];
        }
    }
    return total;
}

int main() {
    int result = calc(1000);
    cout << result << endl;
}

你可能感兴趣的:(C++,贪心算法,算法,c++,python)