Dynamic Programming and Knapsack Application

前端 未结 4 1688
遇见更好的自我
遇见更好的自我 2020-12-29 00:26

Im studying dynamic programming and am looking to solve the following problem, which can be found here http://www.cs.berkeley.edu/~vazirani/algorithms/chap6.pdf:

You

4条回答
  •  清酒与你
    2020-12-29 00:57

    optimize() {

    Rectangle memo[width][height]
    optimize(0,0,totalwidth, totalheight, memo)
    

    }

    optimize(x, y, width, height, memo) {

    if memo[width][height] != null
        return memo[width][height]
    
    rect = new Rectangle(width, height, value = 0)
    for each pattern {
    
        //find vertical cut solution
        leftVerticalRect = optimize (x, y + pattern.height, pattern.width, height-pattern.height,memo)
        rightVerticalRect = optimize(x  + pattern.width, y, width-pattern.width, height)
        verticalcut = new Cut(x + pattern.width, y, x + pattern.width, y + height)
    
        //find horizontal cut solution
        topHorizontalRect = optimize ( --parameters-- )
        bottomHortizonalRect = optimize( --parameters--)
        horizontalcut = new Cut( --parameters--)
    
        //see which solution is more optimal
        if (leftVerticalRect.val + rightVerticalRect.val > topHorizontalRect.val + bottomHorizontalRect.val)
            subprobsolution = vertical cut solution
        else
            subprobsolution = horizontal cut solution
    
        //see if the solution found is greater than previous solutions to this subproblem
        if (subprobsolution.value + pattern.value > rect.value) {
            rect.subrect1 = subprobsolutionrect1
            rect.subrect2 = subprobsolutionrect2
            rect.pattern = pattern
            rect.cut = subprobsolutioncut
            rect.value = rect.subrect1.value + rect.subrect2.value + rect.pattern.value
        }
    }
    
    memo[width][height] = rect
    return rect
    

    }

提交回复
热议问题