Skip to content

Instantly share code, notes, and snippets.

@prodhan
Created January 31, 2019 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prodhan/50dfeaae92371bbe2fdb07d503d151ca to your computer and use it in GitHub Desktop.
Save prodhan/50dfeaae92371bbe2fdb07d503d151ca to your computer and use it in GitHub Desktop.
C++ program to get the maximum total value in the knapsack
/*
* 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