Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- using namespace std;
- int sackCapacity;
- int totalItems;
- int weight_array[100],benifit_array[100];
- int V_knapSack_0_1[100][100];
- void input();
- void print();
- int findMaximum(int,int);
- void knapSack01ArrayDisplay();
- int main(void)
- {
- input();
- print();
- knapSack01ArrayDisplay();
- return 0;
- }
- void input()
- {
- cout<<"Enter sack capacity : ";
- cin>>sackCapacity;
- cout<<"Enter total items : ";
- cin>>totalItems;
- int i;
- for(i=1;i<=totalItems;i++)
- {
- cout<<"Enter item "<<i<<"'s weight and benifit : ";
- int weight_i,benifit_i;
- cin>>weight_i>>benifit_i;
- weight_array[i]=weight_i;
- benifit_array[i]=benifit_i;
- }
- }
- void print()
- {
- int i;
- cout<<"Items (i) : "<<endl;
- for(i=1;i<=totalItems;i++)
- {
- cout<<i<<"\t";
- }
- cout<<endl;
- cout<<"Value/Befinit (val) : "<<endl;
- for(i=1;i<=totalItems;i++)
- {
- cout<<benifit_array[i]<<"\t";
- }
- cout<<endl;
- cout<<"Weight (wt) : "<<endl;
- for(i=1;i<=totalItems;i++)
- {
- cout<<weight_array[i]<<"\t";
- }
- cout<<endl;
- }
- int findMaximum(int a,int b)
- {
- if(a>b)
- {
- return a;
- }
- return b;
- }
- void knapSack01ArrayDisplay()
- {
- int i,w;
- int row_i=totalItems;
- int column_w=sackCapacity;
- for(i=0;i<=row_i;i++)
- {
- for(w=0;w<=column_w;w++)
- {
- if(i==0||w==0)
- {
- V_knapSack_0_1[i][w]=0;
- }
- }
- }
- for(i=0;i<=row_i;i++)
- {
- for(w=0;w<=column_w;w++)
- {
- if(weight_array[i]>w)
- {
- V_knapSack_0_1[i][w]=V_knapSack_0_1[i-1][w];
- }
- else if(weight_array[i]<=w)
- {
- V_knapSack_0_1[i][w]=findMaximum( V_knapSack_0_1[i-1][w] , benifit_array[i]+V_knapSack_0_1[i-1][w-weight_array[i]] );
- }
- }
- }
- cout<<"Knapsack_0_1 matrix : "<<endl;
- for(i=0;i<=row_i;i++)
- {
- for(w=0;w<=column_w;w++)
- {
- cout<<V_knapSack_0_1[i][w]<<"\t";
- }
- cout<<endl;
- }
- cout<<"Final result : "<<V_knapSack_0_1[row_i][column_w]<<endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement