01 Backpack (Zeroonepack): there are n items and a backpack with a capacity of V. (Only one piece per item) The cost of item I is c[i] and the value is w[i]. The sum of the values is maximized by solving which items are loaded into the backpack.
This is the most basic knapsack problem, characterized by: only one piece of each item, you can choose to put or not put.
Define the state with sub-question: F[i][v] Indicates the maximum value that the first I item can get in a backpack with a capacity of V. The state transfer equation is:
F[i][v]=max{f[i-1][v],f[i-1][v-c[i]]+w[i]}
把这个过程理解下:在前i件物品放进容量v的背包时,
它有两种情况:
第一种是第i件不放进去,这时所得价值为:f[i-1][v]
第二种是第i件放进去,这时所得价值为:f[i-1][v-c[i]]+w[i]
(第二种是什么意思?就是如果第i件放进去,那么在容量v-c[i]里就要放进前i-1件物品)
最后比较第一种与第二种所得价值的大小,哪种相对大,f[i][v]的值就是哪种。
(这是基础,要理解!)
这里是用二位数组存储的,可以把空间优化,用一位数组存储。
用f[0..v]表示,f[v]表示把前i件物品放入容量为v的背包里得到的价值。把i从1~n(n件)循环后,最后f[v]表示所求最大值。
* Here F[v] is equivalent to a two-bit array of f[i][v]. So, how to get f[i-1][v] and F[i-1][v-c[i]]+w[i]? Focus Thinking
The first thing to know is that we are using the I from 1 to n loops to indicate the status of the first I item deposited. That is: for I=1..N
Now think about how it can be f[v] that the current state is the value of a backpack with a capacity of V, while the f[v] and F[v-c[i]]+w[i] label the value of the previous state?
reverse order!
That's the point!
Reverse |
For I=1..N for V=v. 0 F[v]=max{f[v],f[v-c[i]]+w[i]}; |
Analyze the above code: when the inner loop is in reverse order, you can guarantee that the latter f[v] and F[v-c[i]]+w[i] is the previous state !
Here are some exercises:
HDU 2546
Http://www.cnblogs.com/sunus/p/4726422.html
HDU 1171
Http://www.cnblogs.com/sunus/p/4726807.html
01 Understanding of the Backpack