Dynamic Planning Primer (2): 01 knapsack problem

_____________________________________________________ good code immortal!

topic:

 

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Title said another: there are N items V and a capacity of the backpack. I into the first space-consuming items C [i], the value obtained is W [i]. Solving the items into a backpack which allows the maximum value of the sum.

The basic idea:

This is the most basic knapsack problem, characterized by: each item is only one, you can select or leave out.

Status subproblem defined by: That indicates just before the i items placed in a maximum capacity value v backpack available. The state transition equation is:

The state transition equation is very important, basically equation backpack with all the relevant questions are derived from it.

Pseudo-code as follows:

F[0,0...V]=0
for i = 1 to N
    for v=C[i] to V
        F[i,v]=max{F[i-1,v],F[i-1,v-C[i]+W[i]}
            

 

_______________________________________________________________________________________________________________________________________

Look turn to the question: ...

The most naked of 01 backpack, to give you the backpack and the total number of items, and the value and volume of items, so you do the most value after backpack filled

 

#include<bits/stdc++.h>
using namespace std;

const int N=1e3+10;
int w[N],v[N],dp[N];
int main()
{
    int T;cin>>T;
    while(T--){
    memset(dp,0,sizeof(dp));
    int N,V;cin>>N>>V;
    for(int i=1;i<=N;i++) cin>>v[i];
    for(int i=1;i<=N;i++) cin>>w[i];
    for(int i=1;i<=N;i++)
    {
        for(int j=V;j>=w[i];j--){
            dp[j]=max(dp[j],dp[j-w[i]]+v[i]);
        }
    }
    cout<<dp[V]<<endl;
    }
    return 0;
}

 

 

 

Chopper can try: https://blog.csdn.net/nobleman__/article/details/78128318

reference:

"Knapsack problem nine stresses"

________________________________________________________ over a thousand waves, you are to the heart.

 

Guess you like

Origin www.cnblogs.com/dragondragon/p/11275514.html