0_1背包
1.从尾部向头部递归
递归
int Knapsack(vector<int>& w, vector<int>& v, int i, int j, int n)//0_1背包,递归写
{
if (i == n)//一个物品
{
return j >= w[i] ? v[i] : 0;
}
else
{
if (j < w[i])return Knapsack(w, v, i + 1, j, n);
else
{
int maxv1 = Knapsack(w, v, i + 1, j, n);
int maxv2 = Knapsack(w, v, i + 1, j - w[i], n)+v[i];
return maxv1 > maxv2 ? maxv1 : maxv2;
}
}
}
非递归
int Knapsack2(vector<int>& w, vector<int>& v, int n, int c, vector<vector<int>>& m)
{
if (n == 0)return 0;
for (int j = 0;j <= c;++j)
{
m[n][j] = j > w[n] ? v[n] : 0;
}
for (int i = n - 1;i >= 1;--i)
{
for (int j = 1;j <= c;++j)
{
if (j >= w[i])
{
m[i][j] = max(m[i + 1][j], m[i + 1][j - w[i]] + v[i]);
}
else
{
m[i][j] = m[i - 1][j];
}
}
}
return m[1][c];
}
int main()
{
const int n = 5;
const int c = 10;
vector<int> w = { 0,2,2,6,5,4 };
vector<int> v = { 0,6,3,5,4,6 };
vector<vector<int>>m(n + 1);
for (int i = 0;i < n + 1;++i)
{
m[i].resize(c + 1);
}
int maxv = Knapsack(w, v, 1, c, n);
int maxv2 = Knapsack2(w, v, n, c, m);
cout << maxv << endl;
}
2.从头部往尾部写
void Knapsack3(vector<int>& w, vector<int>& v, int n, int c, vector<vector<int>>& m)
{
for (int i = 1;i <= n;++i)
{
for (int j = 1;j <= c;++j)
{
if (j < w[i])
{
m[i][j] = m[i - 1][j];
}
else
{
m[i][j] = std::max(m[i - 1][j],m[i - 1][j - w[i]] + v[i]);
}
}
}
}
void print_vect(const vector<vector<int>>& m)
{
for (int i = 0;i < m.size();++i)
{
for (int j = 0;j < m[i].size();++j)
{
printf("%4d", m[i][j]);
}
printf("\n");
}
printf("\n");
}
void backx(vector<int>& w, vector<vector<int>>& m, int n, int c, vector<bool>& X)
{
for (int i = n;i >= 1;--i)
{
if (m[i][c] != m[i - 1][c])
{
X[i] = true;
c = c - w[i];
}
}
}
int main()
{
const int n = 5;
const int c = 10;
vector<int> w = { 0,2,2,6,5,4 };
vector<int> v = { 0,6,3,5,4,6 };
vector<vector<int>>m(n + 1, vector<int>(c + 1, 0));
Knapsack3(w, v, n, c, m);
print_vect(m);
cout << maxv2 << endl;
}