0-1 knapsack(Dynamic Programming).

 #include<bits/stdc++.h>

using namespace std;
#define shailesh ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define ll long long int
#define vi vector<int>
#define pii pair<int, int>
#define vii vector<pii>
#define rep(i, a, b) for(int i=a; i<b; i++)
#define ff first
#define ss second

const int N=1e3+2, MOD=1e9+7;
int val[N], wt[N];

int dp[N][N];

int Knapsack(int n, int w){
    if(w<=0)
    return 0;

    if(n<=0)
    return 0;

    if(dp[n][w]!=-1)
    return dp[n][w];

    if(w<wt[n-1])
       dp[n][w]=Knapsack(n-1, w);
    else
         dp[n][w]=max(Knapsack(n-1, w), Knapsack(n-1, w-wt[n-1])+val[n-1]);
   

    return dp[n][w];


}


int main(){
   
   shailesh

   rep(i, 0, N){
       rep(j, 0, N)
           dp[i][j]=-1;
       
   }

   int n;
   cin>>n;

   rep(i, 0, n)
   cin>>wt[i];

   rep(i, 0, n)
   cin>>val[i];

   int w;
   cin>>w;

   cout<<Knapsack(n,w)<<endl;



return 0;
}

Comments

Popular posts from this blog

priority_queue

Alignment in css

Queue data structure in c++