Given n object with each with some weight and associated value. Find out the maximum value of knapsack if multiple objects with same weight are allowed.
Ex: Value = { 60,100,200}
Weight = {10,20,30}
The idea is to start with the smallest weight and find out the total value of the knapsack for that and then continue with the next weight and consider the maximum value of either current object by adding the previous object value and the weight.
int _tmain(int argc, _TCHAR* argv[])
{
int v[]={60,100,200};
int w[]={15,20,30};
int key = 50;
int n;
std::cout<<"Enter sum value :\n";
std::cin>>n;
int *sum;
sum= new int[50];
sum[0]=0; //base, coins to make a sum of zero.
for(int i = w[0];i<=50;i++)
{
sum[i] = 0;
for(int j=1;j<=3 ;j++)
{
if(w[j-1]<=i)
{
// Consider the case when you add two units and the value is more than the current unit weight.
sum[i] = v[j-1] + sum[i-w[j-1]] > v[j] ? v[j-1] + sum[i-w[j-1]] : v[j];
}
}
}
std::cout<<" Total value of kanpsack of weight "<< n << " is :"<<sum[n-1]<<std::endl;
}
Ex: Value = { 60,100,200}
Weight = {10,20,30}
The idea is to start with the smallest weight and find out the total value of the knapsack for that and then continue with the next weight and consider the maximum value of either current object by adding the previous object value and the weight.
int _tmain(int argc, _TCHAR* argv[])
{
int v[]={60,100,200};
int w[]={15,20,30};
int key = 50;
int n;
std::cout<<"Enter sum value :\n";
std::cin>>n;
int *sum;
sum= new int[50];
sum[0]=0; //base, coins to make a sum of zero.
for(int i = w[0];i<=50;i++)
{
sum[i] = 0;
for(int j=1;j<=3 ;j++)
{
if(w[j-1]<=i)
{
// Consider the case when you add two units and the value is more than the current unit weight.
sum[i] = v[j-1] + sum[i-w[j-1]] > v[j] ? v[j-1] + sum[i-w[j-1]] : v[j];
}
}
}
std::cout<<" Total value of kanpsack of weight "<< n << " is :"<<sum[n-1]<<std::endl;
}
No comments:
Post a Comment