算法导论 ch15 动态规划 01背包

1. source codes

 

#include <iostream> using namespace std; int Knapsack (int *v, int *w, int N, int W) { // table for storing A[j,Y] int *t = new int[N * W]; // table for storing whether stuff i is included under weight j int *flag = new int[N * W]; for (int i = 0; i < N; i++) { flag[i] = 0; for (int j = 0; j < W; j++) { t[i * W + j] = 0; flag[i * W + j] = 0; } } for (int i = 1; i < N; i++) { for (int j = 1; j < W; j++) { if (w[i] > j) { t[i * W + j] = t[(i-1) * W + j]; } else { int t1 = t[(i-1) * W + j]; int t2 = t[(i-1) * W + j - w[i]] + v[i]; if (t1 < t2) { // include stuff i flag[i * W + j] = 1; t[i * W + j] = t2; } else { t[i * W + j] = t1; } } } } for (int i = 0; i < N; i++) { for (int j = 0; j < W; j++) { cout << t[i * W + j]<< " "; } cout << endl; } int i = N - 1; int j = W - 1; while (i > 0) { if (flag[i * W + j] == 1) { cout << "stuff "<< i << " is included"<< endl; j -= w[i]; } i--; } return t[(N - 1) * W + (W-1)]; } int main() { int v[] = { 0, 60, 100, 120 }; int w[] = { 0, 10, 20, 30 }; int n = sizeof(v)/sizeof(int); int W = 50; int maxValue = Knapsack(v, w, n, W + 1); cout << "the max value is " << maxValue << endl; }

 

2. test result

 

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 0 0 0 0 0 0 0 0 0 0 60 60 60 60 60 60 60 60 60 60 100 100 100 100 100 100 100 100 100 100 160 160 160 160 160 160 160 160 160 160 160 160 160 160 160 160 160 160 160 160 160 0 0 0 0 0 0 0 0 0 0 60 60 60 60 60 60 60 60 60 60 100 100 100 100 100 100 100 100 100 100 160 160 160 160 160 160 160 160 160 160 180 180 180 180 180 180 180 180 180 180 220 stuff 3is included stuff 2is included the max value is 220 

 

3. solution

 

From: http://zh.wikipedia.org/zh/%E8%83%8C%E5%8C%85%E9%97%AE%E9%A2%98

0-1背包问题

类似的方法可以解决0-1背包问题 ,算法同样需要伪多项式时间 。我们同样假定w1 , ..., wn W 都是正数。我们将在总重量不超过Y 的前提下,前j 种物品的总价格所能达到的最高值定义为A (j , Y )。

A (j , Y )的递推关系为:

  • A (0, Y ) = 0
  • A (j , 0) = 0
  • 如果wj > Y , A (j , Y ) = A (j - 1, Y )
  • 如果wj Y , A (j , Y ) = max { A (j - 1, Y ), pj + A (j - 1, Y - wj ) }

通过计算A (n , W )即得到最终结果。为提高算法性能,我们把先前计算的结果存入表中。因此算法需要的时间和空间都为O(nW ),通过对算法的改进,空间的消耗可以降至O(W )。

你可能感兴趣的:(算法导论 ch15 动态规划 01背包)