4/06/2017

Geeksforgeeks Solution For " 0 - 1 Knapsack Problem "

GeeksforGeeks Solution For Hard Domain .Below You Can Find The Solution Of  School Basic ,Easy ,Medium . Or Hackerrank Solution You Can Also Direct Submit Your Solution to Geeksforgeeks Same Problem .You Need to login then you can submit you answers 

Problem :- 0 - 1 Knapsack Problem 

Submit Your Solution :- Click Here 

Solution :- 

#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 ;
    int mat[no+1][w+1]={0} ;
   
    for(i=0;i<=no;i++)
        mat[i][0]=0 ;
       
    for(i=0;i<=w;i++)
        mat[0][i]=0 ;
   
    for(i=1;i<=no;i++)
    {
        for(j=1;j<=w;j++)
        {
            if(j>=weight[i-1])
            {
                mat[i][j]=max(mat[i-1][j],val[i-1]+mat[i-1][j-weight[i-1]]) ;
            }
            else if(i>1)
             mat[i][j]=mat[i-1][j] ;
        }
    }
    return mat[no][w] ;
}

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

Output:-



Geeksforgeeks Solution For " 0 - 1 Knapsack Problem "

Ghanendra Yadav

Ghanendra Yadav

Hello, I Am Ghanendra Yadav Owner of This Blog, I am professional Blogger and Programmer. I Love Programming, Logo Making, And Banner Designing. My Highest Qualification is MCA From NIT Warangal. You Can Find Me On Social Media Through Below Link And If You Have Any Query Related To Programming And Other Subject Comment Below or You Can Mail Me I Will Try To Answer Within 24 Hours Email:- yghanendra@student.nitw.ac.in

Find me on Social Media

Facebook | Twitter | Google+ | RSS Feed

No comments:

Post a Comment