Posted on Aug 1
The 0-1 knapsack problem: find the maximum profit \(p\) below, by choosing items to put in the knapsack whose capacity is given by \(w\). There are \(n\) items and each item \(i,\ (1\leq i\leq n)\) has a weight \(w_i\) and a decision variable \(x_i\) that takes 1 if the item \(i\) is selected or 0 otherwise.
The format of the problem input for the above code is:
[The capacity of the knapsack (w)]
[The number of items (n)]
[Weight]
[Profit]
The code above implements psuedo-polynomial time algorithm using dynamic programming. Assuming that \(\mathrm{dp}_{{i - 1},\ {x}}\) holds the solution of the smaller problem with \(n = i - 1\) and \(w = x\), the solution for \(n = i\) and \(w = x\) can be given by the following formula.
And obviously \(\mathrm{dp}_{0,\ x} = 0\).
The solution is \(\mathrm{dp}_{n,\ w}\).
The indices of chosen items in the optimal solution can be obtained by backtracking the above algorithm.
2015 My gh-pages