Programming Algorithm-Knapsack Problem (three types of Dynamic Planning) code (C)
Knapsack Problem (three dynamic plans) code (C)
AvailableDynamic Programming (DP)You can useMemory-based searchPush and export the recursive formula, which can be usedThree different directionsSolve the problem.
Dynamic Planning mainly involvesStatus TransferTo be clear.
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]; // The default value is 0 public: void solve () {for (int I = n-1; I> = 0; I --) {for (int j = 0; j <= W; ++ j) {if (j
Output:
result = 7
Space-saving and usable1-dimensional arrayDynamic Planning.
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] = {2,1,3,2}, v[MAX_N]={3,2,4,2};int dp[MAX_N+1];public:void solve() {memset(dp, 0, sizeof(dp));for (int i=0; i
=w[i]; --j) {dp[j] = max(dp[j], dp[j-w[i]]+v[i]);}}printf(result = %d, dp[W]);}};int main(void){Program P;P.solve(); return 0;}
Output:
result = 7