void branchAndBound(knapsack &k, int maxTime) // Implement a Branch and Bound search for an optimal solution. // Searches for the best decision for objects n and greater, as long // as more than maxTime seconds have not elapsed. Tries // to keep or not keep object n, and then iterates to n+1. Stores // the best solution found so far in bestSolution. { clock_t endTime, startTime = clock(); deque<knapsack> problem; deque<knapsack>::iterator itr; int number,bestValue=0; knapsack bestSolution; double time=0; cout<<"Branching and Bounding"<<endl; // Initially, decisions have not been made about any objects, // so set num = 0. k.setNum(0); // Add the empty knapsack subproblem to the list problem.push_front(k); // Branch and Bound search goes here while (!(problem.empty()) && (time<=maxTime)) //for each object in the deque { k = problem.back(); // current instance is now the last object in the deque while((k.getNum()!=k.getNumObjects()) && (k.bound()> bestValue) && (time<=maxTime)) /*if we haven't considered all the objects left and the bound of the current instance is not worse than our best-so-far solution and we are not out of time*/ { //delete the last object from the deque because we are currently solving it problem.pop_back(); number=k.getNum(); k.setNum(number+1); //we are now considering the next object if(k.getCostBound()-k.getCurrentCost()>k.getCost(number)) { problem.push_back(k); //push the 'don't select' instacne before the take instance k.select(number); } problem.push_back(k); //push the remaining instance endTime=clock();//update current time time=((double)(endTime-startTime))/CLOCKS_PER_SEC; } if (k.getCurrentValue() > bestValue){// replace best values if current ones are better bestValue = k.getCurrentValue(); bestSolution = k; } problem.pop_back(); //delete the last object from the deque since it is fathomed } cout << "Best value found: " << bestValue << endl; cout << bestSolution; k.outFile(bestSolution); }