Cod sursa(job #2963183)

Utilizator OffuruAndrei Rozmarin Offuru Data 10 ianuarie 2023 11:13:52
Problema Problema rucsacului Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <iostream>
#include <fstream>
#include <vector>

struct Object
{
	int weight, value;
	
	Object() { weight = 0, value = 0; }

	Object(int weight, int value)
	{
		this->weight = weight;
		this->value = value;
	}
};

void read(std::vector<Object>& objects, int& maxWeight)
{
	std::ifstream fin("rucsac.in");
	int n;

	fin >> n;
	fin >> maxWeight;
	int weight, value;

	for (int i = 0; i < n; i++)
	{
		fin >> weight >> value;
		objects.push_back({ weight,value });
	}
}

int getMaxValue(const std::vector<Object>& objects,int maxWeight)
{
	std::vector<std::vector<int>> maxValues(objects.size() + 1, std::vector<int>(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");
	int maxWeight;
	std::vector<Object> objects;
	read(objects, maxWeight);
	fout << getMaxValue(objects, maxWeight);
}