我需要编写一个使用蛮力方法的程序来找出如何最有效地进行更改。我有点困惑,我很好奇我是否走在正确的轨道上。我正在用 C 编写它。
它不使用贪心算法。
这只是让我感到困惑。最后,它应该输出最有效的零钱,依次为:toonie、loonie、25th、dimes、nicks、pennies。(如 1 1 0 0 1 0。)
我在正确的轨道上吗?我对自己在做什么有点困惑,六个 for 循环显然是关键,我正在添加每次迭代,但至于概念上发生的事情我有点困惑。
#include <stdio.h>
int main(int argc, char *argv[]) {
//Input
int amount = 336;
int bestSolution = amount;
//Coins
int toonies = 0, loonies = 0, quarters = 0, dimes = 0, nickels = 0, pennies = 0;
int amountAfterToonies, amountAfterLoonies, amountAfterQuarters, amountAfterDimes, amountAfterNickels;
//Counters
int i, j, k, l, m, n;
for (i = 0; i < amount / 200; i++) { //Finds amount
toonies++;
amountAfterToonies = amount % 200;
for (j = 0; j < amountAfterToonies / 100; j++) {
loonies++;
amountAfterLoonies = amountAfterToonies % 100;
for (k = 0; k < amountAfterLoonies / 25; k++) {
quarters++;
amountAfterQuarters = amountAfterLoonies % 25;
for (l = 0; l < amountAfterQuarters / 10; l++) {
dimes++;
amountAfterDimes = amountAfterQuarters % 10;
for (m = 0; m < amountAfterDimes / 5; m++) {
nickels++;
amountAfterNickels = amountAfterDimes % 5;
for (n = 0; n < amountAfterNickels; n++) {
pennies++;
sum = toonies + loonies + quarters + dimes + nickels + pennies;
if (sum < bestSolution) {
bestSolution = sum;
}
}
}
}
}
}
}
printf("%d %d %d %d %d %d\n", toonies, loonies, quarters, dimes, nickels, pennies);
printf("%d\n", bestSolution);
return 0;
}