---
title: "0/1背包问题的动态规划详解"
author: "JAVA凌"
date: "2010-08-04T00:47:33Z"
tags: []
categories: ["编程语言"]
slug: "0-1"
draft: false
lastmod: "2010-08-04T00:47:33Z"
id: 728437
url: "https://xiaoling0.iteye.com/blog/728437"
---

动态规划是用空间换时间的一种方法的抽象。其关键是发现子问题和记录其结果。然后利用这些结果减轻运算量。  
比如01背包问题。

/* 一个旅行者有一个最多能用M公斤的背包，现在有N件物品，  
它们的重量分别是W1，W2，...,Wn,  
它们的价值分别为P1,P2,...,Pn.  
若每种物品只有一件求旅行者能获得最大总价值。  
输入格式：  
M,N  
W1,P1  
W2,P2  
......  
输出格式：  
X  
\*/

因为背包最大容量M未知。所以，我们的程序要从1到M一个一个的试。比如，开始任选N件物品的一个。看对应M的背包，能不能放进去，如果能放进去，并且还有多的空间，则，多出来的空间里能放N-1物品中的最大价值。怎么能保证总选择是最大价值呢？看下表。  
测试数据：  
10,3  
3,4  
4,5  
5,6

![](http://blog.programfan.com/upfile/200711/20071112151236.jpg)

c\[i]\[j]数组保存了1,2,3号物品依次选择后的最大价值.

这个最大价值是怎么得来的呢?从背包容量为0开始,1号物品先试,0,1,2,的容量都不能放.所以置0,背包容量为3则里面放4.这样,这一排背包容量为4,5,6,....10的时候，最佳方案都是放4.假如1号物品放入背包.则再看2号物品.当背包容量为3的时候，最佳方案还是上一排的最价方案c为4.而背包容量为5的时候，则最佳方案为自己的重量5.背包容量为7的时候，很显然是5加上一个值了。加谁??很显然是7-4=3的时候.上一排 c3的最佳方案是4.所以。总的最佳方案是5+4为9.这样.一排一排推下去。最右下放的数据就是最大的价值了。(注意第3排的背包容量为7的时候,最佳方案不是本身的6.而是上一排的9.说明这时候3号物品没有被选.选的是1,2号物品.所以得9.)

从以上最大价值的构造过程中可以看出。

f(n,m)=max{f(n-1,m), f(n-1,m-w\[n])+P(n,m)}这就是书本上写的动态规划方程。

下面给出我们第五次个人赛时出的一道题：

 

Description

Many years ago , in Teddy’s hometown there was a man who was called “Bone Collector”. This man like to collect varies of bones , such as dog’s , cow’s , also he went to the grave …  
The bone collector had a big bag with a volume of V ,and along his trip of collecting there are a lot of bones , obviously , different bone has different value and different volume, now given the each bone’s value along his trip , can you calculate out the maximum of the total value the bone collector can get ?  
  

Input

The first line contain a integer T , the number of cases.  
Followed by T cases , each case three lines , the first line contain two integer N , V, (N &lt;= 1000 , V &lt;= 1000 )representing the number of bones and the volume of his bag. And the second line contain N integers representing the value of each bone. The third line contain N integers representing the volume of each bone.

 

Output

One integer per line representing the maximum of the total value (this number will be less than 231).

 

Sample Input

```

1
5 10
1 2 3 4 5
5 4 3 2 1
```

 

Sample Output

```

14
```

//基础01背包问题，v容量的包，每个物品权值和容量已知求包能装的最大总权值和。  
//f\[i]\[j]表示对于前i个物品，包的容量为j时最大能装的权值和，当然转移的时候对于当前物品  
//只有装和不装两种选择，如果不装则由f\[i-1]\[j],如果装则由f\[i-1]\[j-vol\[i]]转移而来。  
#include&lt;iostream&gt;  
using namespace std;  
#define IN(x) scanf("%d",&x)  
#define max(x,y) x&gt;y?x:y

int value\[1009],volume\[1009];  
int f\[1001]\[1001];

int main()  
{  
 int cnt,n,v,i,j;  
 IN(cnt);  
 while(cnt--)  
 {  
  IN(n);IN(v);  
  for(i = 1; i &lt;= n; i ++) //注意，这边得空出一位来，wa了两次了  
   IN(value\[i]);  
  for(i = 1; i &lt;= n; i ++)  
   IN(volume\[i]);  
  memset(f,0,sizeof(f));  
  for(i = 1; i &lt;= n; i ++)  
   for(j = 0; j &lt;= v; j ++)  
   {  
    if(volume\[i] &lt;= j)  
     f\[i]\[j] = max(f\[i-1]\[j],f\[i-1]\[j-volume\[i]]+value\[i]);  
    else  
     f\[i]\[j] = f\[i-1]\[j];  
   }  
  printf("%d\\n",f\[i-1]\[j-1]);  
 }  
 return 0;  
}

 

 

另外，这也可以用一维数组来简化代码。f\[i]\[v]是由f\[i-1]\[v]和f\[i-1]\[v-c\[i]]两个子问题递推而来，能否保证在推f\[i]\[v]时（也即在第i次主循环中推f\[v]时）能够得到f\[i-1]\[v]和f\[i-1]\[v-c\[i]]的值呢？事实上，这要求在每次主循环中我们以v=V..0的顺序推f\[v]，这样才能保证推f\[v]时f\[v-c\[i]]保存的是状态f\[i-1]\[v-c\[i]]的值。伪代码如下：  
for i=1..N  
for v=V..0  
f\[v]=max{f\[v],f\[v-c\[i]]+w\[i]};  
其中的f\[v]=max{f\[v],f\[v-c\[i]]}一句恰就相当于我们的转移方程f\[i]\[v]=max{f\[i-1]\[v],f\[i-1]\[vc\[i]]}，因为现在的f\[v-c\[i]]就相当于原来的f\[i-1]\[v-c\[i]]。如果将v 的循环顺序从上面的逆序改成顺序的话，那么则成了f\[i]\[v]由f\[i]\[v-c\[i]]推知，与本题意不符，但它却是另一个重要的背包问题：完全背包问题 最简捷的解决方案，故学习只用一维数组解01背包问题是十分必要的。

下面给出本题的一维数组的解法。

#include&lt;iostream&gt;  
using namespace std;  
#define IN(x) scanf("%d",&x)  
#define max(x,y) x&gt;y?x:y

int value\[1009],volume\[1009];  
int f\[1001];

int main()  
{  
 int cnt,n,v,i,j;  
 IN(cnt);  
 while(cnt--)  
 {  
  IN(n);IN(v);  
  for(i = 0; i &lt; n; i ++)  
   IN(value\[i]);  
  for(i = 0; i &lt; n; i ++)  
   IN(volume\[i]);  
  memset(f,0,sizeof(f));  
  for(i = 0; i &lt; n; i ++)  
   for(j = v; j &gt;= 0; j --)  
   {  
    if(volume\[i] &lt;= j)  
     f\[j] = max(f\[j],f\[j-volume\[i]]+value\[i]);  
   }  
  printf("%d\\n",f\[v]);  
 }  
 return 0;  
}