Editorial for COI '13 #4 Nizovi
Submitting an official solution before solving the problem yourself is a bannable offence.
This task can be solved incrementally, meaning that we will take each member of the smaller sequence and insert it into the larger sequence, respectively. At the same time, we are left with the same subproblem with the same characteristics as the original problem and that means we can use the below described procedure multiple times until we're left with a sorted sequence.
Let's observe how it is possible to insert a whole smaller sequence into the larger one so that the first (smallest) element of the smaller sequence is in the right place. For simplicity and clarity, let's observe the following general sequence example:
where lowercase letters mark the elements of the smaller sequence, and the uppercase letters mark the elements of the larger sequence. Using command cmp
, we find the element after which we need to insert element (in other words, we're looking for the biggest element of the larger sequence for which holds ). With the help of binary search, we find the wanted using only operations. Let's assume in this case that the following holds: . If we use command reverse
on all elements between and , we get:
Furthermore, flipping the elements , , we get:
where we can see that the first four elements of the sequence are in their final positions, so we use the same algorithm on the given sequence, only this time we ignore the first four elements. A simple calculation shows that the total cost of all reverse
orders is at most , which is enough for of points on this task.
Complexity:
Comments