杭电骨头收集者

来源:互联网 发布:地瓜淘宝视频下载器 编辑:程序博客网 时间:2024/06/11 15:44
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.

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背包问题,每个骨头只能捡一次。刚开始的时候有的同学可能会理解成贪心,认为只需要挑性价比最高的骨头就可以了,但是仔细思考就会发现,背包可能不必装满就可以获得最大的价值,而且很容易举出一个反例来:当背包容量为3时,看下面的一组输入
1
4 3
8 4 3 3
3 2 1 2
下面给出具体程序#include<stdio.h>
#include<string.h>
int dp[1002];
struct ai
{
int num,val;
}data[1002];
int max(int a,int b)
{
return a>b?a:b;
}
int main()
{
int t,i,j,n,v;
scanf("%d",&t);
while(t--)
{
memset(dp,0,sizeof(dp));
scanf("%d%d",&n,&v);
for(i=0;i<n;i++)
scanf("%d",&data[i].num);
for(j=0;j<n;j++)
scanf("%d",&data[j].val);
for(i=0;i<n;i++)
for(j=v;j>=data[i].val;j--)
{
dp[j]=max(dp[j],dp[j-data[i].val]+data[i].num);
printf("%d",dp[j]);
}
printf("%d\n",dp[v]);
}
return 0;
}

0 0