I have problem with my homework.
Given a board of dimensions m
x n
is given, cut this board into rectangular pieces with the best total price. A matrix gives the price for each possible board size up through the original, uncut board.
Consider a 2 x 2
board with the price matrix:
3 4
3 6
We have a constant cost for each cutting for example 1
.
Piece of length 1 x 1
is worth 3
.
Horizontal piece of length 1 x 2
is worth 4
.
Vertical piece of length 1 x 2
is worth 3
.
Whole board is worth 6
.
For this example, the optimal profit is 9, because we cut board into 1 x 1
pieces. Each piece is worth 3
and we done a 3
cut, so 4 x 3
- 3 x 1
= 9
.
Second example:
1 2
3 4
Now I have to consider all the solutions:
4
1x1
pieces is worth4x1 - (cost of cutting) 3x1 = 1
2
horizontal1x2 is worth 2x2 - (cost of cutting) 1x1 = 3
2
vertical1x2 is worth 3x2 - (cost of cutting) 1x1 = 5
-> best optimal profit1
horizontal1x2 + 2 x (1x1) pieces is worth 2 + 2 - (cost of cutting) 2 = 2
1
vertical1x2 + 2 x (1x1) pieces is worth 3 + 2 - (cost of cutting) 2 = 3
I've read a lot about rod cutting algorithm but I don't have any idea how to bite this problem. Do you have any ideas?
I did this in Python. The algorithm is
best_val
= value of current boardbest_val
best_val
= that sumI'm not sure what you'll want for return values; I gave back the best value and tree of boards. For your second example, this is
Code, with debugging traces (
indent
and the labeledprint
s):Output (profit and cut sizes) for each of the two tests:
Let
f(h,w)
represent the best total price achievable for a board with heighth
and widthw
with cutting pricec
. ThenHere's a bottom-up example in JavaScript that returns the filled table given the price matrix. The answer would be in the bottom right corner.
According to your answers I've prepared bottom-up and top-down implementation.
Bottom-up:
Top-down:
Please tell me are they correct implementation of this method?
I wonder if time complexity is
O(m^2*n^2)
in top-down method?Some thoughts on the problem rather than an answer:
It was a long time ago i studied dynamic programming, but i wrote up the following pseudo code which is think is O(n^2):
The board class is not trivially implemented, here is some elaboration:
It is not clear to me at the moment if
cutOffPiece()
breaks the algorithm in that you do not know how to optimally cut. I think since the algorithm will proceed from larger pieces to smaller pieces at some point it will be fine.I tried to solve the re computation of sub problems (identical boards) by storing results in something like
HashMap<Board, price>
and comparing the new board with the stored best price before proceeding.