With the previousVernacular backpack 01 backpackTo see what a full backpack is. I hope that you can see it clearly in the future. It is best to just drop it if you can help the first child shoes.
I. About All backpacks
There are n items, and each item (with an infinite number of items) corresponds to W [I] and VA [I]. There is a backpack that can put M-weight items. Now, you can choose some items from the N-hour items, which makes the maximum value of backpacking when it does not exceed the upper limit of the backpack.
II. A preliminary understanding of the complete backpack algorithm
Now let's look at the state transition equation:
DP [I] [J] = max {DP [I-1] [J-K * W [I] + K * va [I] | 0 <= K * va [I] <= m}It is understood that when considering the I items, the remaining size of the backpack is the biggest benefit of J.
Look at the code: explain it clearly and then optimize it.
for(int i = 1; i <= N; i ++){ for(int j = w[i]; j <= M; j ++){ int Max = 0; for(int k = 0; k*w[i] <= M; k ++){ Max = max(Max,dp[i-1][j-k*w[i]]+k*va[i]); } dp[i][j] = Max; }}
Let's take a look at how this operation works. For example, if the first item W [1] = 3, VA [1] = 2; then we run the above Code, for example:
Consider the scenario of DP [1] [3] first. Here, we find that K loops can only take 1, so that DP [1] [3] = DP [0] [3-1*3] + 1*2 = DP [0] [0] + 2 = 2; meaning, consider the first item. If the size of the backpack is 3, we can put the first item (if it is more than 3), which maximizes the benefits in this situation.
Similarly, when considering the first item, the other status of the backpack is updated as follows:
We can find that we can only put the first item until the backpack capacity is 6, so when the capacity is 6, we can just put it into two
So here we can find that, in fact, the status of the first item, capacity of 6 DP [1] [6], can be obtained in the status of DP [1] [3, and other statuses are similar...
3: we can introduce optimized one-dimensional arrays to reduce time complexity at the same time.
First, let's look at the algorithm of the one-dimensional array:
for(int i = 1; i <= N; i ++){ for(int j = w[i]; j <= M; j ++){ dp[j] = max(dp[j],dp[j-w[i]]+va[i]); }}
The other States mentioned above are similar. How can they be similar ?, Figure:
So, it turns
When DP [6] is updated, it can be obtained by DP [3] + va [1]. This is similar when other items are considered. So here is the place where the difference 01 is needed... That is, the for loop is from small to large. Because of the Current Status DP [J], we must rely on the existing status (that is, this item must have been put in front of us. Let's put another item to see if we can get more benefits) to update our current status.
OK. This is all done by the backpack.
Personal ignorance. Thank you for your correction and discussion.
Casual backpack full backpack