二维板切割算法

时间:2017-11-21 12:41:45

标签: algorithm dynamic-programming

我的作业有问题。

给定尺寸为m x n的电路板,将此电路板切割成具有最佳总价的矩形片。矩阵通过原始的未切割板为每个可能的板尺寸提供价格。

考虑一个价格矩阵为2 x 2的董事会:

3 4

3 6

我们对每次切割都有不变的成本,例如1
一块1 x 1长度值3
水平长度1 x 24
垂直长度1 x 2值得3
整板价值6

对于这个例子,最佳利润为9 ,因为我们将董事会削减为1 x 1件。每件作品都值3我们完成了3剪辑,因此4 x 3 - 3 x 1 = 9

第二个例子:

1 2

3 4

现在我必须考虑所有解决方案:

  • 4 1x1件值得4x1 - (cost of cutting) 3x1 = 1
  • 2水平1x2 is worth 2x2 - (cost of cutting) 1x1 = 3
  • 2纵向1x2 is worth 3x2 - (cost of cutting) 1x1 = 5 - >最佳利润
  • 1水平1x2 + 2 x (1x1) pieces is worth 2 + 2 - (cost of cutting) 2 = 2
  • 1垂直1x2 + 2 x (1x1) pieces is worth 3 + 2 - (cost of cutting) 2 = 3

我已经阅读了很多关于杆切割算法但我不知道如何咬这个问题。 你有什么想法吗?

4 个答案:

答案 0 :(得分:2)

我是用Python做的。算法是

  • best_val =当前董事会的价值
  • 检查每个水平和垂直切口以获得更好的价值
    • 表示切割点< =当前维度的一半(如果没有,则返回初始值)
    • 重新形成两块板子
    • 如果值的总和> best_val
    • ... best_val =总和
    • ...记录切入点和方向
  • 返回结果:best_val,cut point和direction

我不确定你对返回值的要求是什么;我给了最好的价值和董事会树。对于你的第二个例子,这是

(5, [[2, 1], [2, 1]])

代码,包含调试跟踪(indent和标记的print):

indent = ""
indent_len = 3

value = [[1, 2],
         [3, 4]
        ]

def best_cut(high, wide):
    global indent
    print indent, "ENTER", high, wide
    indent += " " * indent_len

    best_val = value[high-1][wide-1]
    print indent, "Default", best_val
    cut_vert = None
    cut_val = best_val
    cut_list = []

    # Check horizontal cuts
    for h_cut in range(1, 1 + high // 2):
        print indent, "H_CUT", h_cut
        cut_val1, cut_list1 = best_cut(h_cut, wide)
        cut_val2, cut_list2 = best_cut(high - h_cut, wide)
        cut_val = cut_val1 + cut_val2

        if cut_val > best_val:
            cut_list = [cut_list1, cut_list2]
            print indent, "NEW H", h_cut, cut_val, cut_list
            best_val = cut_val
            cut_vert = False
            best_h = h_cut

    # Check vertical cuts
    for v_cut in range(1, 1 + wide // 2):
        print indent, "V_CUT", v_cut
        cut_val1, cut_list1 = best_cut(high, v_cut)
        cut_val2, cut_list2 = best_cut(high, wide - v_cut)
        cut_val = cut_val1 + cut_val2

        if cut_val > best_val:
            cut_list = [cut_list1, cut_list2]
            print indent, "NEW V", v_cut, cut_val, cut_list
            best_val = cut_val
            cut_vert = True
            best_v = v_cut

    # Return result of best cut
    # Remember to subtract the cut cost
    if cut_vert is None:
        result = best_val  , [high, wide]
    elif cut_vert:
        result = best_val-1, cut_list
    else:
        result = best_val-1, cut_list

    indent = indent[indent_len:]
    print indent, "LEAVE", cut_vert, result
    return result

print best_cut(2, 2)

两项测试的输出(利润和削减规模):

(9, [[[1, 1], [1, 1]], [[1, 1], [1, 1]]])

(5, [[2, 1], [2, 1]])

答案 1 :(得分:1)

f(h,w)代表具有高度h和宽度w且切割价格为c的纸板可实现的最佳总价格。然后

f(h,w) = max(
  price_matrix(h, w),
  f(i, w) + f(h - i, w) - c,
  f(h, j) + f(h, w - j) - c
)
for i = 1 to floor(h / 2)
for j = 1 to floor(w / 2)

这是JavaScript中的一个自下而上的示例,它返回给定价格矩阵的填充表。答案就在右下角。



function f(prices, cost){
  var m = new Array(prices.length);

  for (let i=0; i<prices.length; i++)
    m[i] = [];

  for (let h=0; h<prices.length; h++){
    for (let w=0; w<prices[0].length; w++){

      m[h][w] = prices[h][w];

      if (h == 0 && w == 0)
        continue;

      for (let i=1; i<(h+1>>1)+1; i++)
        m[h][w] = Math.max(
          m[h][w],
          m[i-1][w] + m[h-i][w] - cost
        );

      for (let i=1; i<(w+1>>1)+1; i++)
        m[h][w] = Math.max(
          m[h][w],
          m[h][i-1] + m[h][w-i] - cost
        );
    }
  }

  return m;
}

$('#submit').click(function(){
  let prices = JSON.parse($('#input').val());
  let result = f(prices, 1);
  let str = result.map(line => JSON.stringify(line)).join('<br>');
  $('#output').html(str);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="input">[[3, 4],
[3, 6]]</textarea>
<p><button type="button" id="submit">Submit</button></p>
<div id="output"><div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

关于问题而不是答案的一些想法:

很久以前我研究过动态编程,但是我写了下面的伪代码,认为是O(n ^ 2):

// 'Board'-class not included

val valueOfBoards: HashMap<Board, int>

fun cutBoard(b: Board, value: int) : int {

    if (b.isEmpty()) return 0
     if (valueOfBoards[b] > value) {
        return 0;
    } else {
        valueOfBoards[b] = value
    }

    int maxValue = Integer.MIN_VALUE

    for (Board piece : b.getPossiblePieces()) {
        val (cuttingCost, smallerBoard) = b.cutOffPiece(piece)
        val valueGained: int = piece.getPrice() - cuttingCost

        maxValue = Max(maxValue, valueGained + cutBoard(smallerBoard, value + valueGained))
    }

    return maxValue;
}

董事会课程并非简单实施,这里有一些阐述:

// returns all boards which fits in the current board
// for the initial board this will be width*height subboards
board.getPossiblePieces() 


// returns a smaller board and the cutting cost of the cut
// I can see this becoming complex, depends on how one chooses to represent the board.
board.cutOffPiece(piece: Board)

目前我不清楚cutOffPiece()是否打破了算法,因为你不知道如何最佳地削减算法。我认为,因为算法会在某些时候从较大的碎片进展到较小的碎片,所以它会很好。

我尝试通过将结果存储在HashMap<Board, price>之类的内容来解决子问题(相同的电路板)的重新计算,并在继续之前将新电路板与存储的最佳价格进行比较。

答案 3 :(得分:0)

根据您的回答,我已经准备了自下而上和自上而下的实施方案。

自下而上:

function bottomUp($high, $wide, $matrix){
    $m = [];

    for($h = 0; $h < $high; $h++){
        for($w = 0; $w < $wide; $w++){
           $m[$h][$w] = $matrix[$h][$w];

            if($h == 0 && $w == 0){
                continue;
            }

            for($i = 1; $i < ($h + 1 >> 1) + 1; $i++){
                $m[$h][$w] = max(
                    $m[$h][$w],
                    $m[$i - 1][$w] + $m[$h - $i][$w] - CUT_COST
                );
            }

            for($i = 1; $i < ($w + 1 >> 1) + 1; $i++){
                $m[$h][$w] = max(
                    $m[$h][$w],
                    $m[$h][$i - 1] + $m[$h][$w - $i] - CUT_COST
                );
            }            
        }        
    }

    return $m[$high-1][$wide-1];
}

自上而下:

function getBestCut($high, $wide, $matrix){
    global $checked;

    if(isset($checked[$high][$wide])){
        return $checked[$high][$wide];
    }

    $bestVal = $matrix[$high-1][$wide-1];
    $cutVert = CUT_VERT_NONE;
    $cutVal = $bestVal;
    $cutList = [];

    for($hCut = 1; $hCut < 1 + floor($high/2); $hCut++){
        $result1 = getBestCut($hCut, $wide, $matrix);
        $cutVal1 = $result1[0];
        $cutList1 = $result1[1];
        $result2 = getBestCut($high - $hCut, $wide, $matrix);
        $cutVal2 = $result2[0];
        $cutList2 = $result2[1];        
        $cutVal = $cutVal1 + $cutVal2;

        if($cutVal > $bestVal){
            $cutList = [$cutList1, $cutList2];
            $bestVal = $cutVal;
            $cutVert = CUT_VERT_FALSE;
            $bestH = $hCut;
        }

        $checked[$hCut][$wide] = $result1;
        $checked[$high - $hCut][$wide] = $result2;
    }

    for($vCut = 1; $vCut < 1 + floor($wide/2); $vCut++){
        $result1 = getBestCut($hCut, $vCut, $matrix);
        $cutVal1 = $result1[0];
        $cutList1 = $result1[1];
        $result2 = getBestCut($high, $wide - $vCut, $matrix);
        $cutVal2 = $result2[0];
        $cutList2 = $result2[1];        
        $cutVal = $cutVal1 + $cutVal2;   

        if($cutVal > $bestVal){
            $cutList = [$cutList1, $cutList2];
            $bestVal = $cutVal;
            $cutVert = CUT_VERT_TRUE;
            $bestH = $vCut;
        }      

        $checked[$hCut][$vCut] = $result1;
        $checked[$high][$wide - $vCut] = $result2;        
    }

    if($cutVert == CUT_VERT_NONE){
        $result = [$bestVal, [$high, $wide]];
    }else if($cutVert == CUT_VERT_TRUE){
        $result = [$bestVal - CUT_COST, $cutList];
    }else{
        $result = [$bestVal - CUT_COST, $cutList];
    }

    return $result;
}

请告诉我他们是否正确实施了这种方法?

我想知道自上而下的方法中时间复杂度是O(m^2*n^2)吗?