Bone Collector
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 ?
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 231).
Sample Input
1 5 10 1 2 3 4 5 5 4 3 2 1
Sample Output
14
【思路分析】
裸的01背包问题。用了两种方法,第一种是用二维数组,第二种是用滚动数组(一维),两种方法都可以一边输入一边处理。滚动数组的具体操作见小白书。
代码如下:
1、二维数组
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn = 1005;
int n,v;
int vol;
int val[maxn];
int dp[maxn][maxn];
int maxs(int a,int b)
{
return a > b ? a : b;
}
void init()
{
scanf("%d %d",&n,&v);
for(int i = 1;i <= n;i++)
{
scanf("%d",&val[i]);
}
for(int i = 1;i <= n;i++)
{
scanf("%d",&vol);
for(int j = 0;j <= v;j++)
{
dp[i][j] = (i == 1 ? 0 : dp[i - 1][j]);
//dp[i][j]表示把前i个物品放到体积为j的背包中的最大总价值
if(j >= vol)
{
dp[i][j] = maxs(dp[i][j],dp[i - 1][j - vol] + val[i]);
//不要该物品以及要该物品两种情况
}
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
init();
printf("%d\n",dp[n][v]);
}
return 0;
}
2、滚动数组
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn = 1005;
int n,v;
int vol;
int val[maxn];
int dp[maxn];
int maxs(int a,int b)
{
return a > b ? a : b;
}
void init()
{
memset(dp,0,sizeof(dp));
scanf("%d %d",&n,&v);
for(int i = 1;i <= n;i++)
{
scanf("%d",&val[i]);
}
for(int i = 1;i <= n;i++)
{
scanf("%d",&vol);
for(int j = v;j >= 0;j--)
{
if(j >= vol)
{
dp[j] = maxs(dp[j],dp[j - vol] + val[i]);
//滚动数组,dp[j]中相当于保存dp[i - 1][j],dp[j - vol]中相当于保存dp[i - 1][j - vol]
}
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
init();
printf("%d\n",dp[v]);
}
return 0;
}