Knapsack with continuous (non distinct) constraint

后端 未结 7 567
南方客
南方客 2021-02-03 12:05

I watched Dynamic Programming - Kapsack Problem (YouTube). However, I am solving a slightly different problem where the constraint is the budget, price, in double, not integer.

7条回答
  •  长情又很酷
    2021-02-03 12:47

    The answers are not quite correct.

    You can implement a dynamic programm that solves the knapsack problem with integer satisfaction and arbitrary real number prizes like doubles.

    First the standard solution of the problem with integer prizes:

    Define K[0..M, 0..n] where K[j, i] = optimal value of items in knapsack of size j, using only items 1, ..., i
    
    for j = 0 to M do K[j,0] = 0
    for i = 1 to n do
        for j = 0 to M do
            //Default case: Do not take item i
            K[j,1] = K[j, i-1]
            if j >= w_i and v_i+K[j-w, i-1] > K[j, i] then
                //Take item i
                K[j,i] = v_i + K[j-w_i, i-1]
    

    This creates a table where the solution can be found by following the recursion for entry K[M, n].

    Now the solution for the problem with real number weight:

    Define L[0..S, 0..N] where L[j, i] = minimal weight of items in knapsack of total value >= j, using only items 1, ..., i
    and S = total value of all items
    
    for j = 0 to S do L[j, 0] = 0
    for i = 0 to n do
        for j = 0 to S do
            //Default case: Do not take item i
            L[j,i] = L[j, i-1]
            if j >= v_i and L[j-v_i, i-1] + w_i < L[j, i] then
                //Take item i
                L[j, i] = L[j -v_i, i-1] + w_i
    

    The solution can now be found similiar to the other version. Instead of using the weight as first dimension we now use the total value of the items that lead to the minimal weight. The code has more or less the same runtime O(S * N) whereas the other has O(M * N).

提交回复
热议问题