hdu2602Bone Collector ——动态规划(0/1背包问题)

时间:2022-05-20 20:18:26
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
1
5 10
1 2 3 4 5
5 4 3 2 1
 
Sample Output
14
 
现附上AC代码:

#include<iostream>
#include<cstring>
using namespace std;
const int v=1000+10;
const int num=1000+10;
int value[num][2]={0};
int dp[num][v]={0};
void solve(int s,int n)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<=s;j++) //这道题之前一直wrong answer,找了很久都没发现问题,最后在此处找到了根源,原先写的是int j=1;后来改为0就对了,体积竟然可以是0,我也是无语了
{
if(j>=value[i][0])
dp[i+1][j]=max(dp[i][j],dp[i][j-value[i][0]]+value[i][1]);
else
dp[i+1][j]=dp[i][j];
}
}
}

int main()
{
int n,s,t;
cin>>t;
while(t--)
{
cin>>n>>s;
memset(dp,0,sizeof(dp));
memset(value,0,sizeof(value));
for(int i=0;i<n;i++)
cin>>value[i][1];
for(int i=0;i<n;i++)
cin>>value[i][0];
solve(s,n);
cout<<dp[n][s]<<endl;
}
return 0;
}

找到递推关系即可。分情况:1)若可重复使用物品,则是dp[i+1][j]=max(dp[i][j],dp[i+1][j-value[i][0]]+value[i][1])

2)若不可重复使用,则为dp[i+1][j]=max(dp[i][j],dp[i][j-value[i][0]]+value[i][1])

区别是从本行找还是从上一行找