质量 |
价值 |
1 |
60 |
3 |
120 |
2 |
100 |
背包可容纳的质量 |
5 |
#pragma once
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<stack>
using namespace std;
const int MAXSIZE = 3;
class BAGS
{
public:
BAGS() {
}
BAGS(int i) {
if (i == 1) {
init();
}
}
~BAGS() {
}
void init() {
m_weight[0] = 1;
m_value[0] = 60;
m_weight[2] = 2;
m_value[2] = 100;
m_weight[1] = 3;
m_value[1] = 120;
m_bagCapcity = 5;
}
void getMaxValue() {
int maxValue[10];
fill(maxValue, maxValue + 10, 0);
for (int i = 0; i < MAXSIZE; i++)
{
for (int curC = m_bagCapcity; curC >= m_weight[i]; curC--) {
if (maxValue[curC] < maxValue[curC - m_weight[i]] + m_value[i]) {
maxValue[curC] = maxValue[curC - m_weight[i]] + m_value[i];
}
}
}
cout << maxValue[m_bagCapcity] << endl;
}
private:
int m_weight[MAXSIZE], m_value[MAXSIZE];
int m_bagCapcity;
};
void testForBag01() {
BAGS test(1);
test.getMaxValue();
}
- 填表的顺序是先行后列,但列从高到低(二维转化为一维)
- 原转移方程:maxValue( 前i件,bagcapacity ) =
Max { maxValue(前i-1件,bagcapacity),
maxValue( 前i-1件,bagcapacity-w[i] ) + v[i] }