Editorial for COI '13 #4 Nizovi


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.

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:

\displaystyle a \ b \ c \ d \ A \ B \ C \ D \ E \ F \ G \ H

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 a (in other words, we're looking for the biggest element of the larger sequence X for which holds X < a). With the help of binary search, we find the wanted X using only \mathcal O(\log n) operations. Let's assume in this case that the following holds: C < a < D. If we use command reverse on all elements between a and C, we get:

\displaystyle C \ B \ A \ d \ c \ b \ a \ D \ E \ F \ G \ H

Furthermore, flipping the elements [C, A], [d, a], we get:

\displaystyle A \ B \ C \ a \ b \ c \ d \ D \ E \ F \ G \ H

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 \mathcal O(N_a^2 + 2 \cdot N_b), which is enough for 100\% of points on this task.

Complexity: \mathcal O(N_a^2 + 2 \cdot N_b)


Comments

There are no comments at the moment.