3

I have task about knackpack problem. But for each subject in knackpack, we have two sets of weight-value parameters. For example:

  1. Beer 1kg 15$, 2kg 20$
  2. Water 5kg 30$, 10kg 40$

...etc

And we can choose only 1 set of weight-value parameter for each item.

So, what solution I see:

  1. Generated all unique combinations of pair weigth-value from 2 array. In out we have 2n combinations.
  2. For all combination we apply knackpack algorithm, then choose solution with max value - it's a best solution.

About problem - if we have about 10-15 items, it's normal. But we need solve this task for 1000 item, so it's 21000 unique combination.

Generate unique combine:

E=[[],[]]
weight1 = [1 2 3 4 5]
weight2 = [6 7 8 9 10]
for choices in itertools.product([0, 1], repeat=len(off)):
E[0].append([(on[j] if choice else off[j]) for j, choice in enumerate(choices)])
value1 = [10 20 30 40 50]
value2 = [60 70 80 90 100]
for choices in itertools.product([0, 1], repeat=len(off)):
E[1].append([(on[j] if choice else off[j]) for j, choice in enumerate(choices)])

If I do it for 30 item - my VDS go to down.

Please, suggest your solution to this problem.

4

1 回答 1

3

你想用蛮力解决一个 NP 完全问题,更重要的是用大量项目。它在理论上是可行的,但你需要一个永恒的时间来做到这一点。您的问题与python无关,而是与理论计算机科学有关。

背包问题的Wikipedia 页面包含几个关于如何解决它的想法:您可以使用动态规划,甚至搜索解决方案的近似值

动态规划方法基于问题具有最优子结构这一事实:可以从 n-1 个变量问题的最优解构建 n 个变量问题的最优解。

于 2013-07-16T09:52:18.497 回答