InputThe 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.OutputOne 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
题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=2602
题意描述:
第一行输入骨头数N和背包的体积V (N <= 1000 , V <= 1000 )
第二行再输入N个整型数表示对应骨头的体积
最后第三行输入N个整型数表示对应骨头的价值
解题思路:
属于背包问题中的01背包问题,是背包问题的基础,也是能否解决好背包问题的关键。
01背包问题,顾名思义,有N件物品,有对应的体积和价值,问怎么放才能使体积为V的背包中所装的物品价值最大,那么对于每件物品有两个选择,不放入或者放入背包,对应状态为0或者1。
解决问题的总体思路是运用动态规划的思想,对于每一件物品,先判断能否装的下,不能装的下,当前前i件物品放入体积为V的背包,最大价值等于前i-1件物品放入体积为V的背包的价值;能放得下判断
放进去价值更大还是不放进去价值更大。下面的代码使用优化后的方式实现,优化就是使用将二位数组优化为一维数组,遍历时将体积逆置。
代码实现:
1 #include<stdio.h> 2 #include<string.h> 3 struct B 4 { 5 int w,v; 6 }; 7 int main() 8 { 9 int i,t,N,V,f[1010],j; 10 struct B b[1010]; 11 scanf("%d",&t); 12 while(t--) 13 { 14 scanf("%d%d",&N,&V);//注意读题,哪个是体积,哪个是价值 15 for(i=0;i<N;i++) 16 scanf("%d",&b[i].v); 17 for(i=0;i<N;i++) 18 scanf("%d",&b[i].w); 19 memset(f,0,sizeof(f));//全部初始化,不能使用多少初始化多少 20 for(i=0;i<N;i++){ 21 for(j=V;j>=0;j--){ 22 if(j>=b[i].w) 23 f[j] = f[j] > f[j-b[i].w]+b[i].v ? f[j] : f[j-b[i].w]+b[i].v; 24 } 25 } 26 printf("%d ",f[V]); 27 } 28 return 0; 29 }
易错分析:
1、注意读入数据时哪个是体积哪个是价值。
2、注意将f数组全部初始化,不然可能导致无法预计的错误。