Editorial for COCI '13 Contest 6 #3 Kockice
Submitting an official solution before solving the problem yourself is a bannable offence.
Let's observe the function  where 
 represents the height of the middle column (the one with the minimal height) which tells us the number of minimal moves necessary to rearrange the piles in the described way. We can calculate this because then the minimal number of moves is uniquely determined: if a column has more bricks than necessary, we need to remove them and if it is missing bricks, we need to add new bricks.
We have two piles, but it is stated that in the end the corresponding columns have to be of equal heights. Then Mirko's pile is  and Slavko's pile is 
 where 
 and 
 are constants which depend on the height and position of the column.
If we observe the graph of the function  we will notice that the function is decreasing at first, then increasing and it has only one global minimum.
It is easily noticed that this minimum is exactly the first point  for which the following holds: 
. In other words, it is the point where the function starts to increase. Also, we can notice that for every point to the left of 
 the following holds: 
 and for every point to the right of 
: 
. This is why we can locate point 
 using binary search, by comparing the relation of function values of two adjacent points.
Alternative approach
(Bruce Merry)
The first trick is to notice that the slightly odd target shape can be removed from the problem: simply subtract  from element 
 of the inputs (the shortest target shape) and now solve for a flat target. You have 
 numbers and need to find the 
 such that 
 is minimised. This is just the median of the numbers (exercise: prove this, if you don't already know why). The median can be found in 
 time using 
std::nth_element; a binary search is also fast enough.
Comments