ADS
Algorithms and Data Structures
Loading...
Searching...
No Matches
Knapsack.h File Reference

The 0-1 knapsack of section 13.6: \( n \) objects of profit \( p_i \) and volume \( v_i \), positive integers, and a knapsack of capacity \( C \); a set \( S \) of volume at most \( C \) and largest profit. More...

#include "ADS/Contract.h"
#include "ADS/dictionary/ChainedHashTable.h"
#include <algorithm>
#include <cstddef>
#include <deque>
#include <limits>
#include <utility>
#include <vector>
#include "ADS/optimization/impl/Knapsack.tpp"

Go to the source code of this file.

Namespaces

namespace  ADS

Functions

std::pair< long, std::vector< std::size_t > > ADS::knapsack (const std::vector< long > &p, const std::vector< long > &v, long C)
 the best profit and a set of objects, by places, of the 0-1 knapsack
long ADS::knapsackMemo (const std::vector< long > &p, const std::vector< long > &v, long C, long *solved=nullptr)
 the best profit by memoization in a hash table (the zaino() of the book); the number of subproblems solved goes to *solved, if given
long ADS::zaino (const std::vector< long > &p, const std::vector< long > &v, long C, long *solved=nullptr)
 knapsackMemo() under the name of the book

Detailed description

The 0-1 knapsack of section 13.6: \( n \) objects of profit \( p_i \) and volume \( v_i \), positive integers, and a knapsack of capacity \( C \); a set \( S \) of volume at most \( C \) and largest profit.

\( \mathit{DP}[ i ][ c ] \), the best profit of the first \( i \) objects in capacity \( c \), is \( -\infty \) if \( c < 0 \), 0 if \( i = 0 \) or \( c = 0 \), and \( \max\{ \mathit{DP}[ i - 1 ][ c ] , \mathit{DP}[ i - 1 ][ c - v_{i-1} ] + p_{i-1} \} \) otherwise. The volumes here may also be 0, and then the column \( c = 0 \) follows the same maximum instead of being 0.

knapsack() fills the table bottom up in \( \Theta( n C ) \) time and reads the set back; knapsackMemo() (zaino() in the book) is the memoization, top down, which solves only the subproblems it reaches, in a hash table per object, of key \( c \), rather than in a table of \( n C \) places, whose initialization alone would cost \( \Theta( n C ) \); so any capacity up to the largest long is allowed. Either is pseudopolynomial: \( C \) takes \( \log C \) bits of the input.

The contracts [see Contract.h]: profits and volumes of the same objects, none negative, and the capacity not negative; the objects of knapsack() fit and give the profit found. The operations are defined in Knapsack.tpp.

See also
A. Montresor, Algoritmi e Strutture Dati, 2025, section 13.6, https://algoritmicamente.it/materiali/libro/capitoli/cap13.pdf
Author
Donato Meoli
Dipartimento di Informatica
Università di Pisa