Bone Collector(01背包)

时间:2023-01-23 16:57:23

题目链接:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=87125#problem/N

题目:

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 ? 
Bone Collector(01背包)
 

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

分析:

将前i件物品放入容量为j的背包中”这个子问题,若只考虑第i件物品的策略(放或不放),那么

就可以转化为一个只牵扯前i-1件物品的问题。如果不放第i件物品,那么问题就转化为“前i-1件

物品放入容量为j的背包中”,价值为f[i-1][j];如果放第i件物品,那么问题就转化为“前i-1件物品放

入剩下的容量为j-v[i]的背包中”,此时能获得的最大价值就是f[i-1][j-v[i]]再加上通过放入第i件物品获得的价值m[i] .

#include<iostream>
#include<cstring>
using namespace std;
int m[],v[];
int f[][];
int max(int a,int b)
{
if(a>b) return a;
else return b;
}
int main()
{
int t,n,i,j,M;
cin>>t;
while(t--)
{
cin>>n>>M;
for(i=;i<=n;i++)
cin>>m[i];
for(i=;i<=n;i++)
cin>>v[i];
for(i=;i<=n;i++)
for(j=;j<=M;j++)
{
f[i][j]=(i==?:f[i-][j]);
if(j>=v[i])
f[i][j]=max(f[i][j],f[i-][j-v[i]]+m[i]);
}
cout<<f[n][M]<<endl;
}
return ;
}