Uploaded
ACM _ Zhao minghao
The classic question is dynamically planned. There are also several ideas. The optimal idea is to change the order of the second round of the 01 backpack question to obtain the optimal solution of the complete backpack;
This algorithm uses a one-dimensional array. first look at the pseudocode: (the content in the reference backpack 9 Lecture)
for i=1..N
for v=0..V
f[v]=max{f[v],f[v-cost]+weight}
You will find that this pseudo code is different from the pseudo code of the 01 backpack only in the loop order of v. Why is this change feasible? First, let's think about why the v = V .. 0 in P01 should be reversed. This is because we need to ensure that the State f [I] [v] in the I-th loop is recursive from the state f [I-1] [v-c [I. In other words, this is to ensure that each item is selected only once, and to ensure that the policy of "selecting the I-item" is considered, it is based on a sub-result f [I-1] [v-c [I] That has never been selected for item I. Now, the unique feature of a backpack is that each type of item can be an unlimited number of items. Therefore, when considering the policy of "adding a first item, however, you need a sub-result f [I] [v-c [I] that may have been selected for Type I. Therefore, you can use v = 0 .. v. This is why this simple program is established.
It is worth mentioning that the order of the two-layer for loop in the above pseudo code can be reversed. This conclusion may lead to optimization of the algorithm time constant.
This algorithm can also be derived from other ideas. For example, explicitly write the state transition equation for solving f [I] [v-c [I] in the basic idea into the original process, we will find that this equation can be equivalent to this form:
f[i][v]=max{f[i-1][v],f[i][v-c[i]]+w[i]}
This equation is implemented using a one-dimensional array and the above pseudo code is obtained.
The following is the implementation code. The dynamic planning code is very simple. The most important thing is to master the state transition equation:
# Include <cstdio> # include <cstring> # define max (a, B) a> B? A: bconst int maxn = 50001; int dp [maxn]; int main () {int n, m, v, I, j, c, w; scanf ("% d", & n); while (n --) {memset (dp,-10000, sizeof (dp); // pay attention here, in the 01 backpack, the value is initialized to 0. here we need to initialize a relatively large negative number dp [0] = 0; // pay attention here, if this parameter is not set, wa scanf ("% d", & m, & v); for (I = 1; I <= m; I ++) {scanf ("% d", & c, & w); for (j = c; j <= v; j ++) dp [j] = max (dp [j], dp [j-c] + w ); // The state transition equation is also consistent with the 01 backpack.} if (dp [v] <0) printf ("NO \ n"); else printf ("% d \ n ", dp [v]);} return 0 ;}