Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Experiment 2.

Student Name: TUSHAR UID: 20BCS3793


Branch: CSE Section/Group: 20BCS_KRG_WM-1
Semester: 5th Date of Performance: 28thOct,22
Subject Name: DAA Lab Subject Code: 20CSP-312

AIM:Code to implement 0-1 Knapsack using Dynamic Programming

CODE:

#include<iostream>
#include<vector>
usingnamespacestd;

intmax(inta, intb)
{
return (a>b) ? a : b;
}
intknapsack(intC, vector<int>weight, vector<int>value, intn)
{
inti, w;
vector<vector<int>>K(n + 1, vector<int>(C + 1));

for (i = 0; i<= n; i++)


{
for (w = 0; w<= C; w++)
{
if (i == 0 || w == 0)
K[i][w] = 0;
elseif (weight[i - 1]<= w)
K[i][w] = max(value[i - 1] +
K[i - 1][w - weight[i - 1]],
K[i - 1][w]);
else
K[i][w] = K[i - 1][w];
}
}
returnK[n][C];
}

intmain()
{
vector<int>val, wt;
intn = 0, W = 0, x = 0;
cout<<"Enter no of Values"<<endl;
cin>>n;
cout<<"Enter Values"<<endl;
for (inti = 0; i<n; i++)
{
cin>>x;
val.push_back(x);
}
cout<<"Enter weights corresponding to the values"<<endl;
for (inti = 0; i<n; i++)
{
cin>>x;
wt.push_back(x);
}

cout<<"Enter capacity "<<endl;


cin>>W;

cout<<"Result: "<<knapsack(W, wt, val, n);

return0;
}

OUTPUT

TIME COMPLEXITY
O(N*W)

You might also like