HDU-2602___Bone Collector——01背包
原题地址:http://acm.hdu.edu.cn/showproblem.php?pid=2602
Bone Collector
Problem 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 231).
Sample Input
15 101 2 3 4 55 4 3 2 1
Sample Output
14
题目大意:
有T个示例,N块骨头,背包体积容量为V。
输入第三行为每块骨头的价值,第四行为相对应骨头的体积,问可获得最大的价值为多少。
解题思路:
01背包问题,动态规划解决问题即可
代码思路:
另取一组数组来作状态转移
核心:关键在于dp【j】=max(dp[j],dp[j-w[i]]+v[i]) 的状态转移!!
下面再详细讲解!!!
#include<bits/stdc++.h>
using namespace std;
int w[1005];
int v[1005];
int dp[1005];
int main()
{
int t,n,m;
scanf("%d",&t);
while(t--)
{
memset(w,0,sizeof(w));
memset(v,0,sizeof(v));
memset(dp,0,sizeof(dp));
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
scanf("%d",&v[i]);
for(int i=1;i<=n;i++)
scanf("%d",&w[i]);
for(int i=1;i<=n;i++)
{
for(int j=m;j>=0;j--)
{
if(j>=w[i])//注意=号
dp[j]=max(dp[j],dp[j-w[i]]+v[i]); //核心状态转移方程
}
}
printf("%d\n",dp[m]);
}
return 0;
}
/*
1
5 10
1 2 3 4 5
5 4 3 2 1
*/
核心讲解:dp【j】=max(dp[j],dp[j-w[i]]+v[i]);这一行代码联系了上一个状态(dp[j-w[i]])与现在的状态(dp[j])并通过比较,实现了状态转移。下面代码详细解释了这一步骤
for(int i=1;i<=n;i++)
{
for(int j=m;j>=0;j--)
{
if(j>=w[i])//注意=号
dp[j]=max(dp[j],dp[j-w[i]]+v[i]);
}
for(int k=1;k<=m;k++)
printf("%d ",dp[k]);
printf("\n");
}
显示为:
可以看出每次转换时dp数组都在改变,如果没有
for(int j=m;j>=0;j--)
则代码可简单的理解为:背包最多能装下题目中所给的骨头,如体积为10的背包能装下体积分别为5和4的体积一块,但最后其实背包还剩余了体积为1的位置没有讨论,则通过 j-- 进行剩余补充讨论。