1. Problem Description: There is known to have N items and a backpack that can accommodate M weight, the weight of each item i is weight, one can only put it or not put, solve how to put it into the item, can make the backpack The total benefits of items are the largest.
2. Design ideas and analysis: whether or not to form a solution tree, the left subtree means that the right is not loaded, and the right to put it, you can get the best solution by retrieving the problem, and use the node to kill Dinning does not meet the node of the requirements.
(Thank you shadow classmates provide this algorithm)
#include
Struct Good {int Weight; int benefit; INT flag; // can be loaded into marker};
INT number = 0; // INT UPBOUND = 0; int CURP = 0, CURW = 0; // Current Benefits Values and Weight INT Maxweight = 0; Good * Bag = NULL;
Void init_good () {Bag = new good [number];
For (int i = 0; i } INT getBound (int NUM, INT * BOUND_U) // Returns the C limiting boundaries and U limited bounds {for (int W = CURW, P = CURP; Num * Bound_u = p Bag [Num]. Benefit; RETURN (P Bag [NUM]. Benefit * ((Maxweight-W) / Bag [Num] .weight));} Void LCBAG () {int bound_u = 0, Bound_c = 0; // Current Node C Limited and U Limited For (int i = 0; i IF (GetBound (I, & Bound_u)> Bound_c) // Traversed the right sub-tree // If it is loaded, it is determined whether the C limit of the right tree is greater than the C limit of the left subtree root, is loaded {updBound = Bound_u; / / Change already u-limit CURP = CURP BAG [i] .benefit; curw = curw bag [i] .weight; // From existing weight and benefits, add new items BAG [i] .flag = 1; / / Marked as load}} } Void Display () {