## Editorial for COCI '16 Contest 2 #3 Nizin

**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.**

Let's first analyze the suboptimal solutions from the SCORING section.

For of points, the task could have been solved using an exhaustive search. In other words, we could have modified the array in every possible way and, in the end, output the minimal number of moves that lead to the solution. Since we can make different moves on an array of length , and because after each move the length of the array decreases by , we conclude that the complexity of this solution is .

Let's first observe the first and last member of the array. Since we wish to transform the array to a palindrome, the first and the last member must be equal in the end. If they are not equal at the given moment, obviously at least one of them must be joined with its neighbour. This kind of thinking leads us to a recursive formulation of the solution. Let denote the minimal number of moves it takes for elements to transform to a palindrome. Given previous remarks,

where the part written in bold is taken into consideration only if it holds . Let's notice that in each step of the algorithm, the value is equal to the sum of all its predecessors, and is equal to the sum of all its successors, whereas the elements in the middle are not modified. Using a dynamic programming approach, more precisely the memoization technique, the complexity of such a solution is , which is enough for of points.

In order to obtain all points, we need to use the fact that the numbers in the input are positive. As in the previous paragraph, we approach the task from the outside within. When we focus on an interval , we differentiate between a couple of cases:

If it holds , then we don't need to join the outer elements, instead we continue solving the interval .

If it holds , then we surely can't profit from joining elements and because their sum is necessarily larger than that can't be left unjoined. Therefore, we will join elements and and continue solving the interval . We analogously solve the case where .

Since we will decrease the interval for at least in each step of the algorithm, we can conclude that the complexity of the algorithm is , sufficient for all points.

## Comments