std::array<int, n> &value) {
53std::vector<std::vector<int> > maxValue(n + 1,
54std::vector<int>(capacity + 1, 0));
57 intitems =
sizeof(weight) /
sizeof(weight[0]);
58 for(
size_ti = 0; i < items + 1; ++i) {
59 for(
size_tj = 0; j < capacity + 1; ++j) {
60 if(i == 0 || j == 0) {
64}
else if(weight[i - 1] <= j) {
72 intprofit1 = value[i - 1] + maxValue[i - 1][j - weight[i - 1]];
75 intprofit2 = maxValue[i - 1][j];
77maxValue[i][j] = std::max(profit1, profit2);
81maxValue[i][j] = maxValue[i - 1][j];
87 returnmaxValue[items][capacity];
99std::array<int, n1> weight1 = {10, 20, 30};
100std::array<int, n1> value1 = {60, 100, 120};
101 const intcapacity1 = 50;
103capacity1, weight1, value1);
104 const intexpected_max_value1 = 220;
105assert(max_value1 == expected_max_value1);
106std::cout <<
"Maximum Knapsack value with "<< n1 <<
" items is " 107<< max_value1 << std::endl;
111std::array<int, n2> weight2 = {24, 10, 10, 7};
112std::array<int, n2> value2 = {24, 18, 18, 10};
113 const intcapacity2 = 25;
115capacity2, weight2, value2);
116 const intexpected_max_value2 = 36;
117assert(max_value2 == expected_max_value2);
118std::cout <<
"Maximum Knapsack value with "<< n2 <<
" items is " 119<< max_value2 << std::endl;
int maxKnapsackValue(const int capacity, const std::array< int, n > &weight, const std::array< int, n > &value)
Picking up all those items whose combined weight is below the given capacity and calculating the valu...
static void test()
Function to test the above algorithm.
int main()
Main function.
Dynamic Programming algorithms.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4