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
问题简述:
有一个骨头收集家,他喜欢收集各种各样的骨头,他有一个体积为V的骨头收集器,陪伴他收集骨头的旅途,显然,不同的骨头有不同的价值和体积,现在给出每块骨头的价值和体积,你能帮他计算出收集家所能得到的最大价值吗?输入,要求第一行包含一个整数T,代表事件的件数,每一个事件包含三行,第一行包含两个整数N和V,分别代表骨头数量和收集器体积,第二行包含N个整数,代表骨头的价值,第三行对应第二行代表每块骨头的体积,输出一个正整数,代表最大价值。
问题分析:
很纯粹的01背包问题,就是求放进背包所能获得的最大价值。背包之01背包、完全背包、多重背包详解
程序分析:
预先设定一个一维数组pd,用来记住放i种骨头时不同背包体积j所能获得的最大价值.c[j]存放每块骨头的花费,v[i]存放每块骨头的价值,关键部分伪代码如下:
*for 0....i;
for j....0;
pd[j]=max(pd[j],pd[j-c[i]+v[i]) *
程序实现:
#include <iostream>
#include<cmath>
using namespace std;
int main()
{
int T;
cin >> T;
while (T--)
{
int N, C;
int pd[1000];
memset(pd, 0, sizeof(pd));
cin >> N >> C;
int *w = new int[N+1];
int *c = new int[N+1];
for (int i = 1; i <= N; i++)
cin >> w[i];
for (int j = 1; j <= N; j++)
cin >> c[j];
for (int i = 1; i <= N; i++)
for (int j = C; j >= 0; j--)
if (c[i] <= j)
pd[j] = pd[j] > (pd[j - c[i]] + w[i]) ? pd[j] : (pd[j - c[i]] + w[i]);
cout << pd[C] << endl;
delete w;
delete c;
}
}