Box Stack - Dynamic Programming

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:

//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;
}
+4
source share
2 answers

And here is my question - is this optimal?

This is not true.

I tried my code with the same input, except for the depth of the third window I made 0.5.

Here is the result . He gives 15, where the answer should be 10, since no other box can fit on top of the third.

+2

, , , (n-) , .

: {2, 50, 1}, {1, 1, 2}, {1, 3, 3}

( 2- .) getP(boxes, 3) , {1, 1, 2} - , {1, 3, 3}, stackOfBoxes(boxes, 1), , , ( , ), {1, 3, 3} - . stackOfBoxes(boxes, 1) 2, , stackOfBoxes(boxes, 2) , {1, 3, 3} , , 50 > 3.

, stackOfBoxes(boxes, n). , , " , () , <= n". , , . ( ).

( Nelxiost !)

+1

Source: https://habr.com/ru/post/1651812/


All Articles