算法导论 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 , ..., wnW 都是正数。我们将在总重量不超过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 )
  • 如果wjY , A (j , Y ) = max { A (j - 1, Y ), pj + A (j - 1, Y - wj ) }

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值