01 A backpack is the most basic problem. It has the following characteristics: You can choose to put or not to put each item. Define the state with sub-problem: that is, F [I, V] indicates the maximum value that the first I-item can be obtained by placing a backpack with a capacity of V. The state transition equation is:
F [I, V] = max (F [I, V], F [I-1, V-W [I] + V [I])
This equation is very important. Basically all the equations related to the backpack are derived from it. Therefore, it is necessary to explain in detail: "Put the first I items into a backpack with a capacity of V, if you only consider the I-th item Policy (put or not put), you can convert it into a problem related to the first I-1 item. If I-1 items are not placed, the problem is converted to "the first I-1 items are placed in a V-sized backpack". The value is f [I-1; V]. if I items are placed, the problem is converted to "the first I-1 items are placed in the left V-ci backpack ", in this case, the greatest value that can be obtained is f [I-1; V-CI] plus the value wi obtained by placing the I-th item. The pseudocode is as follows:
F [0, 0.. V] <-- 0
For I <-- 1 to n
For v <-- CI to V
F [I; V] <-- max {f [I-1, V], F [I-1, V-CI] + wi}
The Code is as follows:
# Include <stdio. h> # include <stdlib. h> # include <string. h> # define max (x, y) x> Y? X: Y; int V [1001]; // value int W [1001]; // weight int DP [1001] [1001]; int main () {int N, m, I, j; while (scanf ("% d", & M, & N )! = EOF) {memset (DP, 0, sizeof (DP); // initialize for (I = 1; I <= N; I ++) scanf ("% d", & W [I], & V [I]); for (I = 1; I <= N; I ++) // number of items for (j = m; j> = W [I]; j --) // put the backpack DP [I] [J] = max (DP [I-1] [J], DP [I-1] [J-W [I] + V [I]); // compare with printf ("% d \ n ", DP [N] [m]);} return 0 ;}
01 backpack [TEMPLATE]