Friday, February 22, 2013

knapsack problem revisited


#include<iostream>
#include<vector>

using namespace std;

void Knapsack(vector<int> v,vector<int> w,int W)
{
//unbounded
vector<int> m(W);
m[0]=0;
for(int i=1;i<=W;i++)
{
int maximum=0;
for(int j=0;j<w.size();j++)
{
if(i>=w[j])
maximum=max(maximum,v[j]+m[i-w[j]]);
}
m[i]=maximum;
}
//bounded
vector<vector<int>> m2;
m2.resize(v.size());
for(int i=0;i<v.size();i++)
{
m2[i].resize(W);
fill(m2[i].begin(),m2[i].end(),0);
}
for(int i=1;i<v.size();i++)
{
for(int j=0;j<W;j++)
{
m2[i][j]=m2[i-1][j];
if(j>w[i])
m2[i][j]=max(m2[i][j],m2[i-1][j-w[i]]+v[i]);
}
}

}


matrix multiplication chain can also be solved by dp

No comments:

Post a Comment