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
题意:
骨头收集者,骨头都有自己的value(价值)和volume(体积),现在给一个一定容积的袋子,问如何装才能装下最大价值的骨头。
解题思路:典型的01背包问题。
表的第一行是所容纳的体积,表的第一列是每个骨头所占体积,第二列是每个骨头对应的价值。
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | ||
---|---|---|---|---|---|---|---|---|---|---|---|
5 | 1 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 |
4 | 2 | 0 | 0 | 0 | 2 | 2 | 2 | 2 | 2 | 3 | 3 |
3 | 3 | 0 | 0 | 3 | 3 | 3 | 3 | 5 | 5 | 5 | 5 |
2 | 4 | 0 | 4 | 4 | 4 | 7 | 7 | 7 | 7 | 9 | 9 |
1 | 5 | 5 | 5 | 9 | 9 | 9 | 12 | 12 | 12 | 12 | 14 |
代码:
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
int c[1010],w[1010],dp[1010];
int main()
{
int t,n,v,i,j;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&v);
memset(c,0,sizeof(c));
memset(w,0,sizeof(w));
memset(dp,0,sizeof(dp));
for(i=1;i<=n;i++)
scanf("%d",&w[i]);//价值
for(i=1;i<=n;i++)
scanf("%d",&c[i]);//体积
for(i=1;i<=n;i++)
for(j=v;j>=c[i];j--)
dp[j]=max(dp[j],dp[j-c[i]]+w[i]);
printf("%d\n",dp[v]);
}
return 0;
}