Problem Description
Manyyears ago , in Teddy’s hometown there was a man who was called “BoneCollector”. 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 ofcollecting there are a lot of bones , obviously , different bone has differentvalue 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
Thefirst line contain a integer T , the number of cases.
Followed by T cases , each case three lines , the first line contain twointeger N , V, (N <= 1000 , V <= 1000 )representing the number of bonesand the volume of his bag. And the second line contain N integers representingthe value of each bone. The third line
contain N integers representing thevolume of each bone.
Output
Oneinteger per line representing the maximum of the total value (this number willbe less than 231).
Sample Input
1
5 10
1 2 3 4 5
5 4 3 2 1
Sample Output
14
考察点:动态规划—01背包
题目大意:
给定T组测试数据,每组数据给定一个n(n块骨头)和一个V(背包的容量V),接下来给定两行分别输入n块骨头的价值和体积。输出背包能装下的最大价值。
题目解析:
动态规划方程:f(n,m)=max{f(n-1,m),f(n-1,m-w[n])+v(n,m)},根据此递推式可知01背包记录的是当前位置的最优解。
AC代码:
#include<cstdio> #include<cstring> #include<cstring> #include<algorithm> using namespace std; int value[1005],volume[1005];//骨头价值,体积 int dp[1005][1005];//记录背包体积从0到V所装价值最大值 int main() { int T; int n,V; scanf("%d",&T); while(T--) { scanf("%d%d",&n,&V); memset(dp,0,sizeof(dp));//dp数组要初始化为0 for(int i=1;i<=n;i++) { scanf("%d",&value[i]); } for(int i=1;i<=n;i++) { scanf("%d",&volume[i]); } for(int i=1;i<=n;i++) { for(int j=0;j<=V;j++) { if(j<volume[i])//当前背包体积j不能装下体积为volume[i]的骨头 { dp[i][j]=dp[i-1][j]; } else//当前背包体积j能装下体积为volume[i]的骨头 { //选择加或不加当前背包的价值 dp[i][j]=max(dp[i-1][j],dp[i-1][j-volume[i]]+value[i]); } } } printf("%d\n",dp[n][V]); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
HDOJ 2602 Bone Collector--01背包
原文地址:http://blog.csdn.net/weihai1996/article/details/48023409