Editorial for COCI '14 Contest 6 #6 WTF
Submitting an official solution before solving the problem yourself is a bannable offence.
The algorithm described in the task seems nonsensical at first glance. Therefore, we need to uncover it and make it more sensible; we do this with a series of clever observations.
First, let's notice that, regardless of the value of constant , after rotations the array is restored to its initial state. That means that the second part of the algorithm begins operating on the same array as the first part of the algorithm, except that the signs are changed. However, instead of changing the signs, in the second part of the algorithm, we can reduce the sum (instead of increase) by . Effectively, the first and second parts of the algorithm operate on identical arrays.
The next step is ignoring the rotation. Instead of imagining an array that rotates, we can imagine different arrays (calculated by rotating array ) which the first and second parts of the algorithm operate on. On the of these arrays (let's call it ), the first and second parts of the algorithm jointly perform the following:
where is the smaller, and is the larger of the two indices , . The upper difference reminds us of the difference of prefix-sums, except that the difference needs to be reversed. By changing the signs of all elements of array , we get a more familiar relation:
If array contains prefix-sums1 of another array , then the difference of prefix-sums is the sum of the corresponding interval of array . More precisely,
The elements of array for which the upper formula holds are calculated using a simple formula . Notice that array has elements.
In a nutshell: the given algorithm actually adds up intervals in arrays which we can construct. But not just any intervals; the intervals in adjacent arrays are and (after we properly orient them, from smaller to larger boundary). These intervals have a common edge (). If we imagine arrays as rows of a matrix, it follows that the algorithm in fact adds up the path in that matrix that goes through the interval from to in the first row, goes down to the second row, in it goes through the interval from to , goes down to the third row, in it goes through the interval from to and so on until the row, all the while adding up all the elements that it visits in the variable .
Therefore, the task comes down to finding the optimal path in a matrix that goes through an interval from left to right or from right to left in each row, goes down to the following row and continues. This is the actual task, all the rest was camouflage.
This task is solved using dynamic programming. The state is a position (row, column) where we are located and the previous step of the path (left, right or down). If the previous step was left, the next step cannot be right and vice-versa. You can work the details out as an exercise.
1 The prefix-sum of array is equal to the sum of the first elements from .
Comments