Created
January 31, 2019 21:06
-
-
Save prodhan/50dfeaae92371bbe2fdb07d503d151ca to your computer and use it in GitHub Desktop.
C++ program to get the maximum total value in the knapsack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* A c++ program to get the maximum total value in the knapsack | |
* Created By Ariful Islam | |
* Student of Dhaka International University | |
* Batch of E-64 | |
*/ | |
#include<iostream> | |
using namespace std; | |
int max(int a, int b) | |
{ | |
if (a > b) | |
return a; | |
else | |
return b; | |
} | |
int KnapSack(int capacity, int wt[], int val[], int n) | |
{ | |
int i, w; | |
int bag[n+1][capacity+1]; | |
for (i = 0; i <= n; i++) | |
{ | |
for (w = 0; w <= capacity; w++) | |
{ | |
if (i==0 || w==0) | |
bag[i][w] = 0; | |
else if (wt[i-1] <= w) | |
bag[i][w] = max(val[i-1] + bag[i-1][w-wt[i-1]], bag[i-1][w]); | |
else | |
bag[i][w] = bag[i-1][w]; | |
} | |
} | |
return bag[n][capacity]; | |
} | |
int main() | |
{ | |
int capacity, n; | |
cout<<"How many Weight you have to calculate?"<<endl; | |
cin>>n; | |
int val[n], wt[n]; | |
for(int i=0; i<n; i++){ | |
cout<<"Weight "<<i+1<<endl; | |
cin>>wt[i]; | |
cout<<"Value "<<i+1<<endl; | |
cin>>val[i]; | |
cout<<endl; | |
} | |
cout<<"What is the capacity?"<<endl; | |
cin>>capacity; | |
cout<<"The maximum total value in the knapsack: "<< KnapSack(capacity, wt, val, n); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment