Editorial for IOI '09 P4 - Raisins


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

At any moment during the cutting, we have a set of independent sub-problems — blocks of chocolate. If we find the optimal solution for each of the blocks, together we get the optimal solution for the whole chocolate. This clearly hints at a dynamic programming solution.

Each sub-problem we may encounter corresponds to a rectangular part of the chocolate, and it can be described by four coordinates: specifically, two x and two y coordinates — the coordinates of its upper left and lower right corner. Hence we have O(N4) sub-problems to solve.

Now to solve a given sub-problem, we have to try all possible cuts. There are O(N) possible cuts to try — at most N1 horizontal and N1 vertical ones. Each possible cut gives us two new, smaller sub-problems we solve recursively. Obviously, the recursion stops as soon as we reach a 1×1 block.

Assume that someone has given us a function S(x1,y1,x2,y2) that returns the number of raisins in the rectangle given by coordinates (x1,y1) and (x2,y2) in constant time.

Using this function we can solve the entire problem in O(N5). We will use recursion with memoization. Given any of the O(N4) sub-problems, first check the memoization table to see whether we have computed it already. If yes, simply return the previously computed value. Otherwise, proceed as follows: The cost of the first cut is S(x1,y1,x2,y2), which we have supposed can be computed in O(1) time. For each possible placement of the first cut, recursively determine the cost of the remaining cuts in each sub-problem, and pick the optimal choice, storing the answer in the memoization table.

We are only missing one piece of the puzzle: the function S. All possible values can easily be precomputed in O(N4) and stored in an array.

Alternatively, we can use two-dimensional prefix sums: let A be the input array, and let Bx,y=i<xj<yAi,j. The values B are called two-dimensional prefix sums. They can be computed using the formula:

x,y>0:Bx,y=Bx1,y+Bx,y1Bx1,y1+Ax1,y1

Having the two-dimensional prefix sums, we can compute the sum in any rectangle, using a similar formula. The sum in the rectangle with corners (x1,y1) and (x2,y2) is:

S(x1,y1,x2,y2)=Bx2,y2Bx1,y2Bx2,y1+Bx1,y1


Comments

There are no comments at the moment.