Editorial for COCI '10 Contest 2 #4 Knjige
Submitting an official solution before solving the problem yourself is a bannable offence.
Observe that the optimal rearranging protocol will be as follows: choose a book numbered , then put books
(
through
) to the top of the stack. Following is the proof of optimality for such a protocol.
If we put book numbered on the top first, then it is certain that we will have to, at a later point, put each book with number less than
on the top. Otherwise, that book would end up below book
in the final array.
Similarly, if we previously put book on top during our optimal reordering protocol, no other book with a number greater than
is worth putting on top, because we would have to put book
on top again (otherwise, book
would appear below this book in the final array). However, there is no point in moving book
on top twice, since the first movement could be ignored to get a shorter protocol, which means the former one was not optimal, contrary to the initial assumption. It follows that we should not put any book greater than
on top.
Therefore, if is the number of the book we put on top at the start of an optimal protocol, we must put all books numbered less than
, and no other book. It is now clear that these books must be put in order
through
.
After these movements, the first numbers will be
through
, so we are interested if the remainder of the array is sorted making numbers
through
follow. In order for this to be true, all numbers greater than
must form an increasing subsequence in the original array because, by moving numbers
, the relative ordering of other numbers is preserved, and this should be increasing in the final array.
Thus, we can let be any number such that
form an increasing subsequence in the initial array. Clearly, since we seek a solution with a minimal number of movements, we will choose the smallest
such that the above conditions hold.
Note that if has the above property, then
has this property as well, because if
form an increasing subsequence, then this is also true for
. Thus, we can find the minimal
using binary search, or we can look at numbers
and find the greatest of them which does not form a decreasing subsequence with the previous elements of the array.
Comments