You’re given a board of length 'L' and width 'W'. Your task is to break this board into 'L' * 'W' smaller squares, such that the total cost involved in breaking is the minimum possible.
NOTE:The breaking cost of each edge for the board will be given.
The first line of input contains 'T', the number of test cases.
The first line of each test case contains two space-separated integers 'L' and 'W', denoting the length and width of the box.
The second line contains 'L' - 1 space-separated integer, where the 'ith' integer denotes the cost of one horizontal cut between the rows 'i' and 'i' + 1.
The third line contains 'W' - 1 space-separated integer, where the 'ith' integer denotes the cost of one vertical cut between the columns 'i' and 'i' + 1.
Output Format:
The only line of output of each test case should contain an integer denoting the minimum cost required to break the board into 'L' * 'W' squares.
Note:
You don’t need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
2 <= L, W <= 10 ^ 4
1 <= costL[i], costW[i] <= 10 ^ 5
Time Limit: 1 sec
1
3 3
1 2
2 1
11
Start by cutting the vertical column with cost = 2, hence cost becomes 2. Then make two cuts at the horizontal row with the cost = 2, Cost = 2*2 + 2 =6. Then vertically cut two columns with cost = 2, Cost = 6 + 1*2 = 8. Finally make three horizontal cuts with cost = 1. Final cost becomes 8 + 1*3 = 11.
1
2 2
2
1
4
In this case, we’ll be doing a total of 2 cuts. In the first cut, we’ll be cutting the first segment and our cost will now be 1*2 = 2 and in the second and the final cut, we’ll be cutting 2 segments each of cost one. Hence our final cost be 2 + 2*1 = 4.
Try to think of a greedy approach to solve the problem.
This problem can be solved using the greedy approach. By greedy, we mean that we simply start cutting the board along every horizontal and vertical line. But this cutting needs to be in a specific manner. Let’s see how we can do this.
For example:
L = 3 and W = 3
costL = 1 2 and costW = 2 1
O(max(L, W) * log(max(L, W))), where L and W are the length and width of the board respectively.
The Time Complexity to sort the cost of the horizontal cut is O(L * log(L)). The Time Complexity to sort the cost of the vertical cut is O(W * log(W)). Hence, the overall Time Complexity is O(max(L, W) * log(max(L, W))).
O(1).
Constant space is being used. Hence, the overall Space Complexity is O(1).