From 2b0c0e6ac37c7ab433bd33c548f131d980959e8d Mon Sep 17 00:00:00 2001 From: 9389lalit <99964550+9389lalit@users.noreply.github.com> Date: Mon, 30 May 2022 23:11:58 +0530 Subject: [PATCH] Add files via upload --- c++/knapsackcode.cpp | 61 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 c++/knapsackcode.cpp diff --git a/c++/knapsackcode.cpp b/c++/knapsackcode.cpp new file mode 100644 index 0000000..88ec5f2 --- /dev/null +++ b/c++/knapsackcode.cpp @@ -0,0 +1,61 @@ +#include +using namespace std; + + +int knap_Sack(int W, int wt[], int val[], int n) +{ + int i, w; + vector> K(n + 1, vector(W + 1)); + + for(i = 0; i <= n; i++){ + for(w = 0; w <= W; w++){ + if(i == 0 || w == 0){ + K[i][w] = 0; + }else if (wt[i - 1] <= w){ + K[i][w] = fmax(val[i - 1] + + K[i - 1][w - wt[i - 1]], + K[i - 1][w]); + }else{ + K[i][w] = K[i - 1][w]; + } + + } + } + + return K[n][W]; +} + + + +int main(){ + std::ios::sync_with_stdio(false); + cin.tie(NULL); + cout.tie(NULL); + + int n; + cout<<"Enter the number of items\n"; + cin>>n; + + int wt[n],val[n]; + cout<<"Enter the value of items\n"; + + for(int i = 0;i>val[i]; + } + + cout<<"Enter the respective weights of previous items\n"; + + for(int i = 0;i>wt[i]; + } + + int lim; + cout<<"Enter the capacity\n"; + cin>> lim; + + int ans = knap_Sack(lim,wt,val,n); + cout<