2005년 11월 26일 토요일

Example of the Knapsack problem's brute force solution

#include <iostream>

using namespace std;

int main()
{
    int cost[4][3]
        = {{5, 3, 2},
           {7, 5, 3},
           {9, 8, 7},
           {11, 8, 8}};

    int solution_x1 = 0;
    int solution_x2 = 0;
    int solution_x3 = 0;
    int solution_x4 = 0;
    int min = 10000;

    for (int x1 = 1 ; x1 <= 3; x1++)
        for (int x2 = 1 ; x2 <= 3; x2++)
            for (int x3 = 1 ; x3 <= 3; x3++)
                for (int x4 = 1 ; x4 <= 3; x4++)
                    if (x1 + x2 + x3 + x4 == 6)
                    {
                        int total_cost = 0;
                        total_cost = cost[0][x1 - 1]
                                   + cost[1][x2 - 1]
                                   + cost[2][x3 - 1]
                                   + cost[3][x4 - 1];

                        if (total_cost < min)
                        {
                            min = total_cost;
                            solution_x1 = x1;
                            solution_x2 = x2;
                            solution_x3 = x3;
                            solution_x4 = x4;
                        }
                    }

    cout << "x1 : " << solution_x1 << endl;
    cout << "x2 : " << solution_x2 << endl;
    cout << "x3 : " << solution_x3 << endl;
    cout << "x4 : " << solution_x4 << endl;
    cout << "total : " << min << endl;

    return 0;
}

댓글 없음:

댓글 쓰기