Welcome to HBH! If you had an account on hellboundhacker.org you will need to reset your password using the Lost Password system before you will be able to login.

Unbounded Knapsack Problem - C++ Code Bank


Unbounded Knapsack Problem
This is my solution to the Unbounded Knapsack Problem using Dynamic Programming
                /*
	Solution to the Unbounded Knapsack Problem
		using Dynamic Programming

	Implemented by GTADarkDude

	For information on Knapsack Problems, check Wikipedia
*/
#include <iostream>
using namespace std;

//CAPACITY > 0 (Max weight)
const int CAPACITY = 15;
//AMOUNT > 0 (Number of objects)
const int AMOUNT = 5;
struct Object
{
	int weight, value;
};
typedef Object Objects[AMOUNT];
const Objects objects = {{12,4},{2,2},{1,2},{1,1},{4,10}};
//This is the example of Wikipedia (in the upper-right corner)
//value > 0, weight > 0
// (object will never get chosen when value <= 0, object will be chosen an infinite times when weight <= 0)

int fill_element(int memory[], const int c)
{
	int max = 0;
	for(int i=0; i<AMOUNT; i++)
	{
		if(objects[i].weight <= c)
		{
			const int temp = objects[i].value + memory[c-objects[i].weight];
			if(temp > max)
				max = temp;
		}
	}
	return max;
}

void print_solution(const int solution)
{
	cout << "\nIf you take a knapsack with a capacity of " << CAPACITY << " kg. and " << AMOUNT << " objects with the following data:\n";
	for(int i=0; i<AMOUNT; i++)
		cout << i+1 << "\tWeight: " << objects[i].weight << " kg.\tValue: " << objects[i].value << endl;
	cout << "Then the highest value that can be achieved with this knapsack is: " << solution << endl;
}

int main()
{
	cout << "****** Unbounded Knapsack Problem ******\n";
	cout << "*                       by GTADarkDude *\n";
	cout << "****************************************\n";
	int memory[CAPACITY+1];
	memory[0] = 0;

	for(int c=1; c<=CAPACITY; c++)
		memory[c] = fill_element(memory, c);

	print_solution(memory[CAPACITY]);
	return 0;
}

            
Comments
Sorry but there are no comments to display