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 <stdio. h> # include <stdlib. h ># include <vector> 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 < Int> TBL (2, vector <int> (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 ;}