I am currently doing some dynamic programming. I came across a stack of boxes.
Boxes are presented as:
struct Box{
double h;
double w;
double d;
};
And the problem is to create the highest stack of boxes, where each cell in the stack is larger (width and depth) than one above it. Suppose that in this case the boxes cannot be rotated.
I keep the crates in std::vector<Box>. First, I do a stable sort by width, and then by depth, so that whenever I select a box, I will only need to look for the next box that fits.
And here is my question - is this optimal?
I assume that every time I select a box, I need to look for linear time (O (n)) to select the next possible square.
Is there any other way to store boxes that might be better in time complexity?
Any other optimizations are also welcome, of course.
My full code is:
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;
}
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;
}