You have a knapsack with capacity C (weight capacity) and a list of n objects of weights
p[0], p[1], ... p[n-1].
Your goal: put as many objects in your knapsack as possible, without going over its capacity.
Implement in a file sac1.cc the function Sac1() described in file sac1.h:
#ifndef __SAC1_H
#define __SAC1_H
#include <vector>
using namespace std;
// We have a knapsack with capacity C, and objects of weight p[0], p[1], ...
// We want to select as many objects as possible such that the sum of their
// weights remains <= C.
// This function should return the maximum count of objects that can fit.
//
// EXAMPLE: C=12, p=[4, 7, 2, 5, 4, 1, 2, 10]
// -> returns 4 because at most 4 objects can fit
// (for example objects #0, #2, #4 and #6 have total weight
// 4 + 2 + 4 + 2 = 12)
int Sac1(int C, const vector<int>& p);
#endif // __SAC1_H
Test:
rm test.tar.gz; wget --no-cache http://fabien.viger.free.fr/oc/td4/test.tar.gz
tar xf test.tar.gz
make sac1
TO SUBMIT: sac1.cc
Now, the objects are also valued (v[0], v[1], ...)
and can also be taken partially:
for each object, you can choose to put an aribtrary fraction (a number in [0, 1]) of it in the knapsack:
you'll gain the corresponding fraction of its value, while occupying the corresponding fraction of its weight.
Which objects (and what fraction of them) should we choose to maximize the value carried in the
knapsack?
Implement in a file sac2.cc the function Sac2() described in file sac2.h:
#ifndef __SAC2_H
#define __SAC2_H
#include <vector>
using namespace std;
// We have a knapsack with capacity C, and objects of weight p[0], p[1], ...
// and of values v[0], v[1], ...
// This function returns the maximum value that one can carry in the knapsack,
// assuming that each object can be taken fractionally.
//
// EXAMPLE: C=12, p=[4, 7, 2, 5, 5, 1, 10], v=[3.1, 99, 0.1, 0.2, 6.6, 0.4, 111]
// -> Must return 154.5. Explanation:
// the optimal solution is to take object #1 whole (weight 7, value 99)
// and half of object #6 (weight 10, value 111).
// This yield a total weight 7*1 + 10*0.5 = 12, and
// a total value 99*1 + 111*0.5 = 154.5.
double Sac2(int C, const vector<int>& p, const vector<double>& v);
#endif // __SAC2_H
Test: make sac2
TO SUBMIT: sac2.cc