Knapsack problem(背包问题)(包括0-1背包)

问题描述:

1 You have a knapsack that has capacity (weight) C.
2 You have several items I1,…,In.
3 Each item Ij has a weight wj and a benefit bj.
4 You want to place a certain number of copies(可以有重复) of each item Ij in the knapsack so that:
5 The knapsack weight capacity is not exceeded and
6 The total benefit is maximal.

例子,capacity=5:

Item    Weight    Benefit
A 2 60
B 3 75
C 4 90

关键的思路:

Suppose the last such item was Ij with weight wj and benefit bj.
Consider the knapsack with weight (w- wj).
Clearly, we chose to add Ij to this knapsack because of all items
with weight wj or less, Ij had the max benefit bj.


关键公式与算法:

Thus, f(w) = MAX { bj + f(w-wj) | Ij is an item}.
This gives rise to an immediate recursive algorithm to
determine how to fill a knapsack.

例子的解答过程:

 1 f(0) = 0. Why?  The knapsack with capacity 0 can have nothing in it.
2 f(1) = 0. There is no item with weight 1.
3 f(2) = 60. There is only one item with weight 60. Choose A.
4
5 f(3) = MAX { bj + f(w-wj) | Ij is an item}.
6 = MAX { 60+f(3-2), 75 + f(3-3)}
7 = MAX { 60 + 0, 75 + 0 }
8 = 75.
9 Choose B.
10
11 f(4) = MAX { bj + f(w-wj) | Ij is an item}.
12 = MAX { 60 + f(4-2), 75 + f(4-3), 90+f(4-4)}
13 = MAX { 60 + 60, 75 + f(1), 90 + f(0)}
14 = MAX { 120, 75, 90}
15 =120.
16 Choose A.
17
18 f(5) = MAX { bj + f(w-wj) | Ij is an item}.
19 = MAX { 60 + f(5-2), 75 + f(5-3), 90+f(5-4)}
20 = MAX { 60 + f(3), 75 + f(2), 90 + f(1)}
21 = MAX { 60 + 75, 75 + 60, 90+0}
22 = 135.
23 Choose A or B.

0-1背包果断犀利啊。假设最终选还是不选。。哦ye。。


0/1背包问题 --- 其实就是不断的分解的二叉树
B[i, w] = max(V[i-1, w], bi + B[i-1, w-wi])
B[i, w] = { w, b, [1, 2, ..,i] }

关键性解释:B[i, w]
假设有n个物品{1,2, ..., i}, 然后重量{w1, w2, ... wn}, 收益{b1, b2, ..., bn}
B[n, w] : {剩余空间: w, 收益为: 0, 现在还有:[1, 2, 3, ...n没有考虑到底拿不拿]}


思路是:从n开始。我分别做两种假设,我最终的选择拿物品i,还是不拿物品i。然后二者中取最大的。



posted @ 2011-10-15 00:20  Jack204  阅读(516)  评论(0编辑  收藏  举报