Programming Algorithm-complete knapsack problem code (C)
Complete backpack problem code (C)
Question: There are n items whose weight and value are respectively w and v. From these items, select the items whose total weight does not exceed W and find the maximum value of the total value in all the selection schemes.
* You can select any number of items for each item.
Dynamic Planning: Add the largest combination to the array,First time complexity O (nW ^ 2),Second, time complexity O (nW).
Solution 1, max () indicates that either from the above or from the front.
Code:
/** Main. cpp ** Created on: 2014.7.17 * Author: spike * // * eclipse cdt, gcc 4.8.1 */# include
# Include
# Include
# Include
# Include
# Include using namespace std; class Program {static const int MAX_N = 100; int n = 4, W = 5; int w [MAX_N] = }, v [MAX_N] = {3, 2, 4, 2}; int dp [MAX_N + 1] [MAX_N + 1]; public: void solve () {for (int I = 0; I
Output:
result = 10
To save memory, you can useOne-dimensional arraySolve the problem.
Code:
/** Main. cpp ** Created on: 2014.7.17 * Author: spike * // * eclipse cdt, gcc 4.8.1 */# include
# Include
# Include
# Include
# Include
# Include using namespace std; class Program {static const int MAX_N = 100; int n = 3, W = 7; int w [MAX_N] = {3, 4, 2 }, v [MAX_N] = {4, 5, 3}; int dp [MAX_N + 1]; public: void solve () {memset (dp, 0, sizeof (dp )); for (int I = 0; I
Output:
result = 10