The backpack capacity is c, there are n items, and the value of each item is v. The total amount of items required to be loaded does not exceed the backpack capacity.
Input format
The first line gives the backpack capacity c, the number of items n
Next, give the weight and value of n items, separated by spaces
Output
Maximum value
Ideas:
DP classic problem, where two-dimensional DP, the abscissa indicates the item number i is currently considered, the ordinate represents the total capacity of j, we build a row n c + a two-dimensional array of Vector <Vector < int >> Memo ( n, vector < int > (c + 1 , -1 )) , the name of this array is memo.
Then consider the equation of state, there are two strategies, one is to directly consider memo [i] [j] = memo [i- 1 ] [j] without considering the current item, and the other is to consider the current item memo [i] [j] = max (memo [i-1] [j], v [i] + memo [i- 1 ] [jw [i]]) , that is, compare the last transfer directly with the current item if added .
If our backpack capacity is set to 5, the number of items is 3, and the information of the three items is as follows
id | 0 | 1 | 2 |
weight |
1 | 2 | 3 |
value | 6 | 10 | 12 |
So we get a two-dimensional array according to the state transition:
Item id / capacity | 0 | 1 | 2 | 3 | 4 | 5 |
0 | 0 | 6 | 6 | 6 | 6 | 6 |
1 | 0 | 6 | 10 | 16 | 16 | 16 |
2 | 0 | 6 | 10 | 16 | 18 | 22 |
So the biggest value we finally achieved was 22.
Code
1 #include<iostream> 2 #include<algorithm> 3 #include<vector> 4 5 using namespace std; 6 7 int main() 8 { 9 int c, n; 10 11 cin >> c >> n; 12 if (n == 0) 13 return 0; 14 vector<int> w(n); 15 vector<int> v(n); 16 for (int i = 0 ; i <n; i ++ ) 17 { 18 cin >> w [i] >> v [i]; 19 } 20 21 vector <vector < int >> memo (n, vector < int > (c + 1 ,- 1 )); 22 23 for ( int j = 0 ; j <= c; j ++ ) 24 { 25 memo [ 0 ] [j] = (j> = w [ 0 ]? V [ 0 ]: 0 ); // If the current backpack can be put down, it is v [0], otherwise it is 0 26 } 27 28 for ( int i = 1 ; i <n; i ++ ) 29 { 30 for ( int j = 0 ; j <= c; j ++ ) 31 { 32 memo [i] [j] = memo [i- 1 ] [j ]; // The first strategy is to directly ignore the current item 33 if (j> = w [i]) // The second strategy needs to first determine whether the current capacity can fit the current item 34 { 35 memo [i] [j ] = max (memo [i] [j], v [i] + memo [i- 1 ] [j- w [i]]); 36 } 37 } 38 } 39 40 cout << memo[n-1][c]; 41 return 0; 42 }