A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://TheAlgorithms.github.io/C-Plus-Plus/db/d16/0__1__knapsack_8cpp_source.html below:

TheAlgorithms/C++: dynamic_programming/0_1_knapsack.cpp Source File

Go to the documentation of this file. 52 const

std::array<int, n> &value) {

53

std::vector<std::vector<int> > maxValue(n + 1,

54

std::vector<int>(capacity + 1, 0));

57 int

items =

sizeof

(weight) /

sizeof

(weight[0]);

58 for

(

size_t

i = 0; i < items + 1; ++i) {

59 for

(

size_t

j = 0; j < capacity + 1; ++j) {

60 if

(i == 0 || j == 0) {

64

}

else if

(weight[i - 1] <= j) {

72 int

profit1 = value[i - 1] + maxValue[i - 1][j - weight[i - 1]];

75 int

profit2 = maxValue[i - 1][j];

77

maxValue[i][j] = std::max(profit1, profit2);

81

maxValue[i][j] = maxValue[i - 1][j];

87 return

maxValue[items][capacity];

99

std::array<int, n1> weight1 = {10, 20, 30};

100

std::array<int, n1> value1 = {60, 100, 120};

101 const int

capacity1 = 50;

103

capacity1, weight1, value1);

104 const int

expected_max_value1 = 220;

105

assert(max_value1 == expected_max_value1);

106

std::cout <<

"Maximum Knapsack value with "

<< n1 <<

" items is " 107

<< max_value1 << std::endl;

111

std::array<int, n2> weight2 = {24, 10, 10, 7};

112

std::array<int, n2> value2 = {24, 18, 18, 10};

113 const int

capacity2 = 25;

115

capacity2, weight2, value2);

116 const int

expected_max_value2 = 36;

117

assert(max_value2 == expected_max_value2);

118

std::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