Hello,everyone.Today i want to show you the 0-1 Knapsack problem,which is based on dynamic programming.Although i can solve this problem,but i still do not have a good command at the dynamic programming.So i want to take it done in three days.Do not believe it?I will show you.^_^
Have fun coding,i_human.Have fun coding,everyone!
THE CODE:
#include<iostream>
#define a 100
using namespace std;
int b[a][a];
int re[a];
int put(int v[],int we[],int n,int w);
int main()
{
int n,w;
int we[a];
int v[a];
cin>>n>>w;
for(int i=1;i<=n;i++)
{
cin>>v[i];
cin>>we[i];
}
for(int i=1;i<a;i++)
for(int j=1;j<a;j++)
b[i][j]=-1;
put(v,we,n,w);
for(int i=1;i<=n;i++)
cout<<re[i]<<" ";
cout<<endl<<put(v,we,n,w);
system("pause");
return 0;
}
int put(int v[],int we[],int n,int w)
{
if(b[n][w]!=-1)
return b[n][w];
if(n==1 && w>=we[1])
{
b[1][w]=v[1];
re[n]=1;
return v[1];
}
else if(n==1 && w<we[1])
{
b[1][w]=0;
re[n]=0;
return 0;
}
else
{
if(v[n]+put(v,we,n-1,w-we[n])>put(v,we,n-1,w) && w-we[n]>=0)
{
re[n]=1;
b[n][w]=v[n]+put(v,we,n-1,w-we[n]);
return v[n]+put(v,we,n-1,w-we[n]);
}
else
{
re[n]=0;
b[n][w]=put(v,we,n-1,w);
return put(v,we,n-1,w);
}
}
}