Http://www.cnblogs.com/fly1988happy/archive/2011/12/13/2285377.html:
1. The optimal solution for "just full of backpacks" is required:
During initialization, Except f [0] is 0, F [1 .. v] is set to-∞, which ensures that the final f [N] is an optimal solution just filled with a backpack. If the capacity of the backpack cannot be satisfied, that is, the optimal value of F [v] cannot be obtained. Then, F [v] =-∞ means that the optimal value of the backpack capacity is not found.
2. Find the optimal solution that is smaller than or equal to the capacity of the backpack, that is, not necessarily full of the backpack:
If you do not need to fill your backpack, but want to maximize the value as much as possible, you should set f [0.. V] to 0 during initialization.
# Include <cstdio> # include <cstring> # include <iostream> # define maxn 1010 using namespace STD; int f [maxn]; const int INF =-0x3ffffff; int main () {// freopen ("in.txt", "r", stdin); int N, V, value [maxn], wei [maxn], CAS; CIN> CAS; while (CAS --) {CIN> N> V; For (INT I = 1; I <= N; I ++) CIN> value [I]; for (INT I = 1; I <= N; I ++) CIN> wei [I]; memset (F, 0, sizeof (f )); for (INT I = 1; I <= N; I ++) {for (Int J = V; j> = wei [I]; j --) f [J] = max (F [J], F [J-wei [I] + value [I]);} cout <F [v] <Endl;} return 0 ;}