好吧,先上题目!
Bone Collector
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 26403 Accepted Submission(s): 10692
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 …
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 ?
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.
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背包问题的题目,然后,这道题我用的是二维数组写的(这样便于理解),最后呢,在做题是发现了些问题,在最后我会说明的,总之了,先附代码!
# include <iostream>
# include <cstdio>
# include <cstring>
# include <algorithm>
using namespace std;
const int inf = 1009;
int valu[inf]; ///骨头的价值
int w[inf]; ///骨头的体积
int f[inf][inf];
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int n,v;
memset(f,0,sizeof(f)); ///初始化二维数组f全部为0
scanf("%d%d",&n,&v);
for(int i=1; i<=n; i++)
{
scanf("%d",&valu[i]);
}
for(int i=1; i<=n; i++)
{
scanf("%d",&w[i]);
}
for(int i=1; i<=n; i++)
{
for(int j=0; j<=v; j++) ///这里要注意,体积是可以为0的!
{
if(j-w[i]<0) ///如果j-w[i]小于0则表示这块骨头体积太大,放不下
{
f[i][j] = f[i-1][j];
}
else
{
f[i][j] = max(f[i-1][j],f[i-1][j-w[i]]+valu[i]);
}
///cout<<f[i][j]<<" ";
}
///cout<<endl;
}
printf("%d\n",f[n][v]);
}
return 0;
}
先说一下01背包的重要代码!其实吧也就是一条了,在下面。
f[i][j] = max(f[i-1][j],f[i-1][j-w[i]]+valu[i])
PS:注意max是函数!
再说下01背包的思想,其实也就是通过比较放入与不放入的大小把价值大的留下来,然后把各个体积的价值留下来!
最后说下出现的问题吧!最大的问题就是体积的循环了,刚开始我用的循环是
for(int j=w[i]; j<=v; j++)
其实这样是不可以的,因为在后面的数据可能用到前面的数据,然而我却去掉了0到w[i]-1的步骤;
还有要注意的一个地方,那就是有的骨头可能没体积,但是有价值!
以上!