Pagini recente » Cod sursa (job #1477994) | Cod sursa (job #197206) | Cod sursa (job #2924827) | Cod sursa (job #1347995) | Cod sursa (job #2963178)
#include <iostream>
#include <fstream>
#include <vector>
struct Object
{
float weight, value;
Object() { weight = 0.0, value = 0.0; }
Object(float weight, float value)
{
this->weight = weight;
this->value = value;
}
};
void read(std::vector<Object>& objects, float& maxWeight)
{
std::ifstream fin("rucsac.out");
int n;
fin >> n;
fin >> maxWeight;
float weight, value;
for (int i = 0; i < n; i++)
{
fin >> weight >> value;
objects.push_back({ weight,value });
}
}
float getMaxValue(const std::vector<Object>& objects,float maxWeight)
{
std::vector<std::vector<float>> maxValues(objects.size() + 1, std::vector<float>(maxWeight + 1));
for (int i = 0; i <= objects.size(); i++)
for (int w = 0; w <= maxWeight; w++)
if (!i || !w)
maxValues[i][w] = 0;
else if (w >= objects[i - 1].weight)
maxValues[i][w] = std::max(objects[i - 1].value + maxValues[i - 1][w - objects[i - 1].weight],
maxValues[i - 1][w]);
else
maxValues[i][w] = maxValues[i - 1][w];
return maxValues[objects.size()][maxWeight];
}
int main()
{
std::ofstream fout("rucsac.out");
float maxWeight;
std::vector<Object> objects;
read(objects, maxWeight);
fout << getMaxValue(objects, maxWeight);
}