ADS
Algorithms and Data Structures
Loading...
Searching...
No Matches
FractionalKnapsack.h

The real (fractional) knapsack of section 14.1. More...

Files

file  ADS/optimization/FractionalKnapsack.h
 The real (fractional) knapsack of section 14.1: a fraction \( x_i \in [ 0 , 1 ] \) of each object, of largest profit \( \sum_i p_i x_i \) and volume \( \sum_i v_i x_i \le C \).

Functions

std::vector< double > ADS::fractionalKnapsack (const std::vector< double > &p, const std::vector< double > &v, double C)
 the fractions \( x \) of the objects, by decreasing \( p_i / v_i \) (the zaino() of the book)

Detailed description

The real (fractional) knapsack of section 14.1.

The definitions, the invariants and the costs of the area are in Theory of optimization.

Function documentation

◆ fractionalKnapsack()

std::vector< double > ADS::fractionalKnapsack ( const std::vector< double > & p,
const std::vector< double > & v,
double C )
inline

the fractions \( x \) of the objects, by decreasing \( p_i / v_i \) (the zaino() of the book)

In pseudocode (section 14.1), the ratios compared as \( p_a v_b > p_b v_a \), with no division:

\[\class{pseudocode}{\begin{array}{r@{\quad}l} 1 & \textbf{function}\ \mathrm{fractionalKnapsack}( p , v , C )\quad \triangleright\ x_i \text{ the fraction of the object } i \cr 2 & \quad x \gets ( 0 , \ldots , 0 ) \cr 3 & \quad \textbf{foreach}\ i \text{, by decreasing profit per unit } p_i / v_i \text{, while } C > 0\ \textbf{do} \cr 4 & \qquad x_i \gets \min\{ 1 , C / v_i \};\ C \gets C - x_i v_i\quad \triangleright\ \text{only the last one may be split} \cr 5 & \quad \textbf{return}\ x \end{array}} \]

Precondition
\( |p| = |v| \), \( v_i > 0 \), \( p_i \ge 0 \), \( C \ge 0 \)
Postcondition
fractions in \( [ 0 , 1 ] \) of volume at most \( C \)