TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
|
Implementation of [0-1 Knapsack Problem] (https://en.wikipedia.org/wiki/Knapsack_problem) More...
#include <array>
#include <cassert>
#include <iostream>
#include <vector>
Go to the source code of this file.
Namespaces | |
namespace | dynamic_programming |
Dynamic Programming algorithms. | |
namespace | Knapsack |
Implementation of 0-1 Knapsack problem. | |
Functions | |
template<size_t n> | |
int | dynamic_programming::knapsack::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 value of those picked items. Trying all possible combinations will yield the maximum knapsack value. | |
static void | test () |
Function to test the above algorithm. | |
int | main () |
Main function. | |
Implementation of [0-1 Knapsack Problem] (https://en.wikipedia.org/wiki/Knapsack_problem)
Given weights and values of n items, put these items in a knapsack of capacity W
to get the maximum total value in the knapsack. In other words, given two integer arrays val[0..n-1]
and wt[0..n-1]
which represent values and weights associated with n items respectively. Also given an integer W which represents knapsack capacity, find out the maximum value subset of val[]
such that sum of the weights of this subset is smaller than or equal to W. You cannot break an item, either pick the complete item or don’t pick it (0-1 property)
The idea is to consider all subsets of items and calculate the total weight and value of all subsets. Consider the only subsets whose total weight is smaller than W
. From all such subsets, pick the maximum value subset.
Definition in file 0_1_knapsack.cpp.
int main | ( | void | ) |
Main function.
Definition at line 126 of file 0_1_knapsack.cpp.
int dynamic_programming::knapsack::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 value of those picked items. Trying all possible combinations will yield the maximum knapsack value.
n | size of the weight and value array |
capacity | capacity of the carrying bag |
weight | array representing the weight of items |
value | array representing the value of items |
Definition at line 51 of file 0_1_knapsack.cpp.
|
static |
Function to test the above algorithm.
Definition at line 96 of file 0_1_knapsack.cpp.