I am currently practicing some dynamic programming. I came across the Stack of Boxes.
The boxes are represented as:
struct Box{
double h;
double w;
double d;
};
And the problem is creating the highest stack of boxes where each box in the stack is larger (in both width and depth) than the one above it. Let's assume that in this case boxes cannot be rotated.
I am storing the boxes in a std::vector<Box>. I am first doing a stable sort by width and then by depth, so that whenever I pick a box I will only need to search forward for the next box that fits.
And here is my question - Is this optimal?
I guess that every time I picked a box I need to search linear time (O(n)) in order to pick the next possible box.
Is there a different way to store the boxes that might be better in time complexity?
Any other optimizations are also welcome of course.
My full code:
//Get index of next box that fits or -1 if none
int getP(std::vector<Box>& boxes, int n){
double n_w = boxes[n].w;
double n_d = boxes[n].d;
for (int i=n-1; i >= 0; i--){
if (n_w > boxes[i].w && n_d > boxes[i].d)
return i;
}
return -1;
}
//Get highest possible stack.
double stackOfBoxes(std::vector<Box>& boxes, int n, Box* bottom){
if (n == -1)
return 0;
if (bottom == NULL || (bottom->d > boxes[n].d && bottom->w > boxes[n].w))
return max(stackOfBoxes(boxes, n-1, bottom),stackOfBoxes(boxes, getP(boxes,n), &boxes[n])+boxes[n].h);
else
return stackOfBoxes(boxes, n-1, bottom);
}
int main(){
std::vector<Box> boxes = { {3,1,1},{5,2,2},{10,7,7} };
std::stable_sort(boxes.begin(), boxes.end(), sortByW);
std::stable_sort(boxes.begin(), boxes.end(), sortByD);
cout << stackOfBoxes(boxes, 2, NULL) << endl;
}