什么是01背包问题呢?下面是弱的理解~~~~~
01背包:0背包是指在n件物品中取出若干件放在空间为V的背包里,每件物品的体积为v1,v2,v3……v(n),与之对应的价值为p1,p2,p3……p(n),求在不超过背包容量的情况下,获得最大价值的方案?
01背包有个特点哟:每种物品只有一件,可以选择放或者不放
状态转移方程:F[i][V]=max{F[i-1][V],F[i-1][V-v[i]]+p[i]}
现在来解释一下上面这个最关键的状态转移方程!
当前背包容量为v,即将处理第i件物品。显然有如下两种方案:
a.若第i件物品加入背包,装入这前i件物品获得的最大价值F[i][V],必然等于第i件物品的价值p[i]再加上向容量为V-p[i]的背包装入前i-1件物品这个子问题的最大价值F[i-1][V-p[i]] (先把第i件物品加入背包,然后考虑安排剩余的空间容量)
b.若不加入第i件物品,装入这前i件物品的获得的最大价值F[i][V],必然等于向容量为V的背包装入前i-1件物品这个子问题获得的最大价值F[i-1][V]
显然,当前问题的最大价值F[i][V]取上面两种方案的较大值!
for(i=1;i<=N;i++)
{
for(j=1;j<=V;j++)
{
if(j>=v[i])
f[i][j]=max(F[i-1][j-v[i]]+p[i],F[i-1][j]);
else F[i][j]=F[i-1][j];
}
}
这个动态规划的时空复杂度都是O(N*V)。
空间复杂度优化
状态转移方程:F[v]=max{F[V],F[V-v[i]]+p[i]}
由于每次迭代计算F[i][V]时,需要知道的子问题只是F[i-1][v]和F[i-1][V-v[i]],即只需要知道前一次的迭代状态序列F[i-1]。那么可以优化空间只使用一个一维数组F[V]不断迭代,将空间复杂度降到O(V)。
for(i=1; i<=n; i++)
for(j=V; j>=v[i]; j--)
{
f[j] = f[j]>(f[j-v[i]] + p[i])? f[j]:(f[j-v1[i]] + p[i]);
}
下面来举个栗子
http://acm.hdu.edu.cn/showproblem.php?pid=2602
E - Bone Collector
Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
Submit Status
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 <= 1000 , V <= 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 2 31).
Sample Input
1
5 10
1 2 3 4 5
5 4 3 2 1
Sample Output
14
题意:题意分析:一个骨头搜集爱好者,收集各类各样的骨头,这个骨头爱好者有一个大袋子,容积是一定的,现给出一定的骨头,每个骨头的容积和价值是固定的,现在我们往袋子中装入骨头,求袋子容积所能承受的条件下的可装的最大价值。
典型的01背包问题:
AC代码如下:
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#define LL 1001int main()
{
int t,n,v,i,j,f[LL],p[LL],v1[LL];
while(scanf("%d",&t) != EOF)
{
while(t--)
{
scanf("%d %d",&n,&v);
memset(f, 0, sizeof(f));
for(i=1; i<=n; i++)
scanf("%d",&p[i]);
for(i=1; i<=n; i++)
scanf("%d",&v1[i]);
for(i=1; i<=n; i++)
for(j=v; j>=v1[i]; j--)
{
f[j] = f[j]>(f[j-v1[i]] + p[i])? f[j]:(f[j-v1[i]] + p[i]);
}
printf("%d\n",f[v]);
}
}
return 0;
}