This is the simplest question about backpacks. This question should be a test point except for a backpack: Two-dimensional arrays cannot be opened. I haven't opened a two-dimensional architecture, but it's impossible to read data. It's too big.
There are two ways to improve the province memory DP:
1. So-called scrolling Array
2 reverse table Filling
I haven't done a backpack DP for a long time. I suddenly think this kind of backpack problem is very simple.
The following two solutions are provided:
1 calBag () is a rolling Array
2 calBag2 () is a reverse table Filling
# Pragma once # include
# Include
# Include
Using namespace std; const int MAX_W = 12881; const int MAX_N = 3403; int N, M; // M is total weightint wei [MAX_N]; int desi [MAX_N]; int tbl [MAX_W]; int calBag2 () {memset (tbl, 0, sizeof (int) * (M + 1); for (int I = 1; I <= N; I ++) {for (int j = M; j> = wei [I]; j --) tbl [j] = max (tbl [j], tbl [j-wei [I] + desi [I]);} return tbl [M];} int calBag () {vector
> Tbl (2, vector
(M + 1); bool id = true; for (int I = 1; I <= N; I ++) {for (int j = 1; j <wei [I] & j <= M; j ++) tbl [id] [j] = tbl [! Id] [j]; for (int j = wei [I]; j <= M; j ++) {tbl [id] [j] = max (tbl [! Id] [j], tbl [! Id] [j-wei [I] + desi [I]);} // note that all data in the previous column is pulled down! Id series comparison id =! Id;} return tbl [! Id] [M];} int main () {while (scanf ("% d", & N, & M )! = EOF) {for (int I = 1; I <= N; I ++) {scanf ("% d", & wei [I], & desi [I]);} printf ("% d \ n", calBag2 ();} return 0 ;}