Pagini recente » Cod sursa (job #2701602) | Cod sursa (job #3268063) | Cod sursa (job #3250201) | Cod sursa (job #1362697) | Cod sursa (job #3281979)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
struct BackpackObj{
int weight, value;
};
int main(){
ifstream fin("rucsac.in");
ofstream fout("rucsac.out");
int obj_count, backpack_capacity;
fin >> obj_count >> backpack_capacity;
vector<BackpackObj> objects(obj_count);
for (int i = 0; i < obj_count; ++i)
fin >> objects[i].weight >> objects[i].value;
vector<vector<int>> dynamic_matrix(obj_count + 1, vector<int>(backpack_capacity + 1));
// max(backpack without object i,
// backpack with object i (which means we take the maximum of the backpack with a decreased capacity))
for (int i = 1; i <= obj_count; ++i)
for (int j = 1; j <= backpack_capacity; ++j)
dynamic_matrix[i][j] = max(dynamic_matrix[i - 1][j],
dynamic_matrix[i - 1][j - objects[i - 1].weight] + objects[i - 1].value);
fout << dynamic_matrix.back().back() << '\n';
}