/**************************************************************** * Program Solving the KNAPSACK problem using a heurustic * * Author Jakub Holy * * For the subject PAA, LS2002 * **************************************************************** */ #include "hw1_heuristic.hh" #include <iomanip.h> // --------------------------------------------- CONST etc. HeurItem::HeurItem(int id, Item& it) : Item (it.weight, it.cost){ HeurItem::id = id; ratio = it.cost / it.weight; }//HeurItem constr // ---------------------------------------------------------- KnapsackProblem::KnapsackProblem(int task_id, int nr_items, int max_load, Item **items){ // Parameters KnapsackProblem::task_id = task_id; KnapsackProblem::nr_items = nr_items; KnapsackProblem::max_load = max_load; KnapsackProblem::items = items; // Init other fields solution = new bool[nr_items]; // normally shall be init. to false manually ... load = 0; cost = 0; // The Vector // 1. Init the vector: insert items for(int i=0; i < nr_items; i++){ item_vect.push_back( *(new HeurItem(i, *(items[i])))); }// items -> item_vect // 2. Sort the items sort(item_vect.begin(), item_vect.end(), OptimalityCriterium() ); } // constructor KnapsackProblem::~KnapsackProblem(){ delete [] items; delete [] solution; } //destructor // --------------------------------------------- SOLVE void KnapsackProblem::solve(void){ int index = 0; for (TItem_vect::iterator iter = item_vect.begin(); iter != item_vect.end(); ++iter) { // Include the item, if not too heavy. if( ( load + iter->weight ) <= max_load ){ solution[index] = true; // include the item load += iter->weight; // add its weight to the total load cost += iter->cost; // add its cost to the total one } else { solution[index] = false; }//if-else index++; }// for all elements in the vector }//solve // --------------------------------------------- PRINT void KnapsackProblem::printResult(void){ assert( solution!=0 ); cout << cost<<endl; }//printResult //****************************************************************** MAIN int main(int argc, char **argv){ //Open data file and load the 1st task if ( argc != 2 ) { cout << "Error: Wrong number of parameters.\n"; cout << "Use: bruteforce taskfile\n";
}// if wrong input KnapsackInput *in = new KnapsackInput( argv[1] ); // For all tasks in the file: do { // Solve a task KnapsackProblem *problem = new KnapsackProblem(in->getTaskID(), in->getNr_items(), in->getMax_load(), in->getItems() ); problem->solve(); problem->printResult(); } while ( in->loadNextTask() ); //--------- return 0; }// main