Knapsack with Duplicate Items

PROBLEM :
Given weights and values related to n items and the maximum capacity allowed for these items. What is the maximum value we can achieve if we can pick any weights any number of times for a total allowed weight of W?

Input:
The first line of input contains an integer denoting the no of test cases. Then T test cases follow . Each test case contains two integers N and W denoting the no of items and the total allowed weight. In the next two lines are space separated values of the array denoting values of the items (val[]) and their weights (wt[]) respectively.

Output:
For each test case in a new line print the  maximum value which we can achieve if we can pick any weights any number of times for a bag of size W.

Constraints:
1<=T<=100
1<=N, W<=1000
1<=wt[], val[]<=100

Example:
Input:
2
2 3
1 1
2 1
4 8
1 4 5 7
1 3 4 5

Output:
3
11

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
int max(int ,int ) ;
int Knapsack_Problem(int [],int [],int ,int ) ;
int main()
 {
int t,no,w,val[100],weight[100],i ;
cin>>t ;
while(t--)
{
   cin>>no ;
   cin>>w ;
 
   for(i=0;i<no;i++)
       cin>>val[i] ;
     
   for(i=0;i<no;i++)
       cin>>weight[i] ;
     
   no=Knapsack_Problem(val,weight,no,w) ;
   cout<<no<<endl ;
}
return 0;
}

int Knapsack_Problem(int val[],int weight[],int no,int w)
{
    int i,j,p ;
    int mat[w+1]={0} ;
   
    for(i=0;i<=w;i++)
    {
        for(j=0;j<no;j++)
        {
            if(weight[j]<=i)
                mat[i]=max(mat[i],mat[i-weight[j]]+val[j]) ;
        }
    }
    return mat[w] ;
}

int max(int a,int b)
{
    return a>b?a:b ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )