hdu2602Bone Collector - dynamic programming (0/1 knapsack problem)

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 2 31).
 

 

Sample Input
1 5 10 1 2 3 4 5 5 4 3 2 1
 

 

Sample Output
14
 
A copy of AC codes:

#include <the iostream>
#include <CString>
the using namespace STD;
const int = 1000 + 10 V;
const int NUM = 1000 + 10;
int value [NUM] [2] = {0};
int DP [NUM] [V ] = {0};
void Solve (S int, int n-)
{
for (int I = 0; I <n-; I ++)
{
for (int J = 0; J <= S; J ++) // This question before has been wrong answer, looking for a long time did not find the problem, and finally found the root cause here, originally written int j = 1; later changed to 0 on the right, the volume can actually be zero, I was speechless
{
IF ( J> = value [I] [0])
DP [I +. 1] [J] = max (DP [I] [J], DP [I] [J-value [I] [0]] + value [I ] [. 1]);
the else
DP [. 1 + I] [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;
}

Find recurrence relations can be. Points: 1) If a reusable article is dp [i + 1] [j] = max (dp [i] [j], dp [i + 1] [j-value [i] [0]] + value [i] [1]) 

                                                 2) If not reusable, compared dp [i + 1] [j] = max (dp [i] [j], dp [i] [j-value [i] [0]] + value [i] [ 1])

The difference is still looking to find from the line from the Bank

Guess you like

Origin www.cnblogs.com/sunjianzhao/p/11372852.html