当前位置:
首页 >
HDU2602 (0-1背包)
发布时间:2023/12/1
46
豆豆
生活随笔
收集整理的这篇文章主要介绍了
HDU2602 (0-1背包)
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
Bone Collector
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 39259 Accepted Submission(s): 16261
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 231).
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的背包,使背包里的价值最大。 0-1背包的模板题,可以有两种解法。 一维数组: #include<stdio.h> #include<string.h> #include<algorithm> using namespace std; int w[1100],p[1110]; int f[1110]; int main() {int t,n,v;scanf("%d",&t); while(t--){scanf("%d%d",&n,&v);for(int i=1;i<=n;i++)scanf("%d",&w[i]); //输入物品重量 for(int i=1;i<=n;i++)scanf("%d",&p[i]); //输入物品价值 memset(f,0,sizeof(f));for(int i=1;i<=n;i++) {for(int j=v;j>=w[i];j--) //这个循环保证了放进去的物品重量不会超过背包所能容纳的重量 {if(f[j] < f[j-w[i]] + p[i]) // 如果当前所拥有价值 小于 加上这件物品时创造的价值就更新 f[j]= f[j-w[i]] + p[i]; // f[j] 表示背包重量为 j 时背包里的最大价值,// 所以f[ j - w[i] ] 表示放进这件物品时的状态(因为放进该件物品后容量就减少了) }} printf("%d\n",f[v]);} return 0; }
二维数组:
1 #include<stdio.h> 2 #include<string.h> 3 #include<algorithm> 4 using namespace std; 5 int w[1100],p[1110]; 6 int f[1110][1110]; 7 int main() 8 { 9 int t,n,v; 10 scanf("%d",&t); 11 while(t--) 12 { 13 scanf("%d%d",&n,&v); 14 for(int i=1;i<=n;i++) 15 scanf("%d",&p[i]); 16 for(int i=1;i<=n;i++) 17 scanf("%d",&w[i]); 18 memset(f,0,sizeof(f)); 19 for(int i=1;i<=n;i++) 20 { 21 for(int j=0;j<=v;j++) 22 { 23 if(w[i]<=j) // 这件物品的重量小于当前的容量,也就是说放的进背包 24 { 25 // f[i][j] 表示第 i 件物品在背包容量为 j 时的状态, 26 //所以 f[i-1][j] 表示背包在上一次容量为 j 时候的状态,也就是没放这件物品的时候 27 f[i][j]=max(f[i-1][j],f[i-1][j-w[i]]+p[i]);// 比较 没放进去之前 和放进该物品后 的价值,取最大 28 29 } 30 else f[i][j]=f[i-1][j]; // 如果不能放进该物品,则取上一次的状态 31 } 32 } 33 printf("%d\n",f[n][v]); 34 } 35 return 0; 36 }
渣渣一枚,如果有什么不对的地方,还请各位大神批评指正~ (^_^)
转载于:https://www.cnblogs.com/ember/p/4701035.html
总结
以上是生活随笔为你收集整理的HDU2602 (0-1背包)的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: cf越光宝盒怎么用?
- 下一篇: Struts学习之手动验证