Problem 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 …<br>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 ?<br><center><img src=../../../data/images/C154-1003-1.jpg> </center><br>
Input
The first line contain a integer T , the number of cases.<br>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<sup>31</sup>).
题意:给出骨头的种类和背包的大小,让你输入骨头的价值和体积,求在不超过背包的体积的前提下的最大价值。
思路:
这里用一个结构体数组表达每个骨头对象,c,w代表体积和价值。f[v]代表体积为v时的最大价值;递归方程:f[j]=max(f[j],f[v-a[i].c]+a[i].w)
代码:
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
const int maxm=1001;
const int maxv=1001;
struct bone
{
int w;
int c;
}a[maxm];
int main()
{
int f[maxv];
int n,m,v;
cin>>n;
while(n--)
{
cin>>m>>v;
memset(a,0,sizeof(a));
for(int i=0;i<m;i++)
cin>>a[i].w;
for(int j=0;j<m;j++)
cin>>a[j].c;
memset(f,0,sizeof(f));
for(int i=0;i<m;i++)
for(int j=v;j>=a[i].c;j--)
{
//f[j]=max(f[j],f[v-a[i].c]+a[i].w);
if(f[j]<f[j-a[i].c]+a[i].w)
f[j]=f[j-a[i].c]+a[i].w;
}
cout<<f[v]<<endl;
}
return 0;
}
感想:这里的空间细节优化要注意,
空间优化:
for i=1..N
for v=V..0
f[v]=max{f[v],f[v-c[i]]+w[i]};
初始化细节:
若要求恰好装满背包,初始化时除了f[0]为0其它f[1..V]均设为-∞
若没有要求必须把背包装满,初始化时将f[0..V]全部设为
for i=1..N
for v=V..0
f[v]=max{f[v],f[v-c[i]]+w[i]};
初始化细节:
若要求恰好装满背包,初始化时除了f[0]为0其它f[1..V]均设为-∞
若没有要求必须把背包装满,初始化时将f[0..V]全部设为