码迷,mamicode.com
首页 > 其他好文 > 详细

动态规划——01背包

时间:2020-02-04 00:21:29      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:main   color   include   http   present   number   namespace   初学者   ems   


 

Bone Collecter

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 ?
技术图片

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

都说01背包是动态规划最经典的问题,初学者大都学起来很费解。我感觉确实是这样,学了好一阵子才搞懂。但是我身边有好些人一下就学会让我心里有些难受。

动态规划最关键的是把状态方程正确的表示出来,这也是动态规划的难点。

状态转移方程清楚的展示了需要解决的问题和它的子问题之间的关系。

在01背包的题目中,设v[i]为第i个物体的价值,w[i]为第i个物品的体积,dp[i][j]表示把前i个物品放入体积剩余j的背包能获得的最大价值。

假设现在我们拿着第i件物品,现在讨论我们是否要把它放入体积剩余j的背包中。

第一种情况:w[i]>j,这时候第i件物品放不进去,所以此时d[i][j]=d[i-1][j];

第二种情况:w[i]<=j,即可以把第i件物品放进去,那我们怎么决定放与不放呢?

假设把第i件物品放入背包,那d[i][j]=d[i-1][j-w[i]]+v[i],就是把前i-1件物品放入体积剩余j-w[i]的背包能得到的最大价值加上v[i];

假设不放,那d[i][j]=d[i-1][j]。当然我们是要得到最大的d[i][j],所以取d[i][j]=max(d[i-1][j-w[i]]+v[i],d[i-1][j])即可。

代码如下:

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<algorithm>
 4 #include<cstring>
 5 using namespace std;
 6 const int M=1e3+1;
 7 int dp[M][M];
 8 int v[M],w[M],n,cap;
 9 
10 int main()
11 {
12     int T;
13     scanf("%d",&T);
14     for(int t=0;t<T;t++)
15     {
16         memset(dp,0,sizeof(dp));
17         memset(v,0,sizeof(v));
18         memset(w,0,sizeof(w));
19         scanf("%d%d",&n,&cap);
20         for(int i=1;i<=n;i++)scanf("%d",&v[i]);
21         for(int i=1;i<=n;i++)scanf("%d",&w[i]);
22         for(int i=1;i<=n;i++)
23         {
24             for(int j=0;j<=cap;j++)
25             {
26                 if(w[i]>j)dp[i][j]=dp[i-1][j];
27                 else {
28                     dp[i][j]=max(dp[i-1][j],dp[i-1][j-w[i]]+v[i]);
29                 }
30             }
31         }
32         printf("%d\n",dp[n][cap]);
33     }
34 }

动态规划——01背包

标签:main   color   include   http   present   number   namespace   初学者   ems   

原文地址:https://www.cnblogs.com/hialin545/p/12257883.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!