Editorial for COCI '11 Contest 4 #4 Ograda


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.

Let's mark the i^\text{th} smallest board that Mirko has with A_i, and i^\text{th} board in the final arrangement with C_i. The niceness of Mirko's fence is equal to the sum of absolute differences between adjacent boards:

\displaystyle |C_1-C_2| + |C_2-C_3| + \dots + |C_{N-1}-C_N|

Since we know the orderings of each two adjacent boards, this sum can be rewritten without absolute values.

If we proceed to reduce this expression to canonical form, every C_i will appear next to an integer coefficient from the interval [-2, 2].

If we put board A_1 next to the smallest of these coefficients, A_2 next to the second smallest and so on, we would surely end up with the fence as nice as possible.

Now we must arrange boards in this way, but also in a way that assures that Mirko's fence is similar to Slavko's.

We use this algorithm:

  1. Coefficients +2 and -2. Boards with these coefficients are larger (smaller) than both boards adjacent to them. There are no adjacent positions with +2 (or -2) coefficient, so we can go and place largest boards next to +2's, and smallest boards next to -2's. It's easy to see that we won't violate any constraint by doing this.

  2. Coefficients +1 and -1. Only the first and the last board can have +1 or -1, so we put the largest board that's left from the first step next to +1 and the smallest one next to -1.

  3. Coefficient 0. These boards are smaller than one neighbour and larger than the other. By placing any of these boards next to boards already positioned in steps 1 and 2, we won't violate anything. So we only must be careful when placing them next to one another. Consecutive sequences of boards with coefficient 0 will be either strictly increasing or strictly decreasing, depending on adjacent boards at the beginning and at the end of the sequence. We place them in any way that satisfies this condition and we are done.


Comments

There are no comments at the moment.