Optimal purchase algorithm

an algorithm for shopping cart, the general flow is:

know the price and importance level of each item (1 to 5 are the most important). In the case of a limited amount, you can buy one or more goods, each with a quantity of 1, achieving the highest points (price x importance).

raise chestnut:
A Commodity: price 100RMB, important level 3
B Commodity: price 350, important level 2
C Commodity: price 800, important level 5
D Commodity: price 550, important level 1

Total amount of account: 3000 yuan

introduce four items of ABCD, and figure out which one or several items to buy has the highest score. Who has the idea of algorithm? Thank you!

Mar.03,2021

this is a knapsack problem . Dynamic programming is used to solve the knapsack problem. If you nest two loops, one state transition equation can produce the result. Specifically, you can take a look at this article 01 knapsack problem . Post his code:

-sharpinclude<iostream>
-sharpinclude<algorithm>
using namespace std;

int main()
{
    const int N = 6;                     //
    const int V = 10;                    //
    int C[N + 1] = { -1,5,6,5,1,19,7 };  //i1
    int W[N + 1] = { -1,2,3,1,4,6,5 };   //i
    int F[N + 1][V + 1] = { 0 };         //

    for (int i = 1; i <= N; iPP)  //i
        for (int v = 0; v <= V; vPP)
        {
            F[i][v] = F[i - 1][v];  //i
            if (v - C[i] >= 0 && F[i][v] < F[i - 1][v - C[i]] + W[i])  //i
                F[i][v] = F[i - 1][v - C[i]] + W[i];
        }

    cout << ":" << F[N][V] << endl;  //9

    return 0;
}

I hope I can help you.

Menu