What's the fastest way to solve knapsack prob with two properties

不羁岁月 提交于 2019-12-01 21:59:07

问题


Let's say we've got an input:

10 // saying 1st property should be 10(in total)
10 // saying 2d property should be 10 (in total)
5 // saying theres 5 records below
// (1st property) (2nd property) (cost)
2 5 8 
7 3 10 
4 2 9
4 3 5
8 5 15

In this case, the output would look like that:

22 // lowest possible cost
1 3 4 // indexes of records, we've been using (indexing starts with 1)

 2  5  8
 4  2  9
 4  3  5
+---------
 10 10 22

If there wasn't possible way to achieve those properties to be 10 and 10, program would output -1; I do know how to solve knapsack problem, however I've got no clue how to solve this prob.


回答1:


You can use the same approach of knapsack problem, but instead of 2D matrix, you will have a 3D table, a dimension for each parameter (2 constraint + index).

The recursive formula will be similar, but of course will be done for both parameters.

f(item,cost1,cost2) = max {
               f(item-1,cost1,cost2), 
               f(item,cost1-firstCost[i],cost2-secondCost[i]) + profit[i]
                          }

(Base clauses will be similar as well, but with an extra dimension.)



来源:https://stackoverflow.com/questions/13404173/whats-the-fastest-way-to-solve-knapsack-prob-with-two-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!