Box stacking problem

后端 未结 5 1831
灰色年华
灰色年华 2020-11-28 20:01

I found this famous dp problem in many places, but I can not figure out how to solve.

You are given a set of n types of rectangular 3-D boxes, where

5条回答
  •  执念已碎
    2020-11-28 20:33

    I think you can solve this using the dynamic programming longest increasing subsequence algorithm: http://www.algorithmist.com/index.php/Longest_Increasing_Subsequence

    Accounting for the rotations is easy enough: for every tower all you have to check is what happens if you use its height as the length of the base and its width as the height and what happens if you use it in the natural way. For example:

    =============
    =           =
    =           =
    =           = L
    =     H     =
    =           =
    =           =
    =============   
          W
    

    Becomes something like (yeah, I know it looks nothing like it should, just follow the notations):

    ==================
    =                =
    =                =  
    =       W        = L
    =                =
    =                =
    ==================
            H
    

    So for each block you actually have 3 blocks representing its possible rotations. Adjust your blocks array according to this, then sort by decreasing base area and just apply the DP LIS algorithm to the get the maximum height.

    The adapted recurrence is: D[i] = maximum height we can obtain if the last tower must be i.

    D[1] = h(1);
    D[i] = h(i) + max(D[j] | j < i, we can put block i on top of block j)
    
    Answer is the max element of D.
    

    See a video explaning this here: http://people.csail.mit.edu/bdean/6.046/dp/

提交回复
热议问题