我需要写一个程序,使用暴力的方法,找出如何使改变最有效。我有点困惑,我很好奇自己是否走对了路。我用C语言写的。
它不使用贪婪算法。
只是让我困惑而已。最后,它应该按照这个顺序输出最有效的变化,如toonie、loonie、quarter、dimes、nickels、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;
}

最佳答案

你找不到最有效的方法你找到了所有的方法。
我建议你这样做:

toonies=amount/200;
amount%=200;
loonies=amount/100;
amount%=100;
//and so on

(即使您想保留循环,也要将它们分开-没有理由使用嵌套循环)

关于c - 我正在编写关于变更的蛮力算法,但有点卡住了,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9304019/

10-11 21:16