Editorial for COI '11 #4 Trampolin


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.

Depending on Kickass's starting position, we can distinguish two cases:

Case #1 (appearing in 20\% of test data): it is impossible to reach any trampoline.

At first glance, we might think that it is enough to simply compare the number of skyscrapers visitable by moving as far as possible to the left versus to the right. However, there are two additional possibilities: moving left visiting all skyscrapers with the same height as the starting one and then moving all the way to the right, as well as the mirror case of this. It is easy to check both possibilities and choose the better one.

Case #2 (appearing in 20\% of test data): at least one trampoline is reachable.

Let us assume that A, B, \dots, M are indices of all skyscrapers which contain a trampoline or have at least one trampoline reachable from them. We will call such skyscrapers beautiful. Notice that the starting skyscraper (K) is among them according to the assumption. Let T(A), T(B), \dots, T(M) be the corresponding reachable skyscrapers with trampolines (not necessarily distinct).

Consider the following path:

\displaystyle \begin{align*}
K &\to \dots \to T(K) \to \\
A &\to \dots \to T(A) \to \\
B &\to \dots \to T(B) \to \\
\vdots & \\
M &\to \dots \to T(M)
\end{align*}

This path is guaranteed to visit all beautiful skyscrapers. After that, we need to visit the longest possible sequence of non-beautiful skyscrapers (ones with no reachable trampoline); we can reach any such sequence using T(M). The total solution is then the sum of the number of beautiful skyscrapers and the length of the longest non-beautiful skyscraper sequence.

We can implement this solution in several steps:

  1. We first mark all skyscrapers containing a trampoline as beautiful.
  2. Traversing the skyscrapers from left to right, we mark skyscraper i as beautiful if skyscraper i-1 is beautiful and we can jump from i to i-1.
  3. Traversing the skyscrapers from right to left, we mark skyscraper i as beautiful if skyscraper i+1 is beautiful and we can jump from i to i+1.
  4. For all skyscrapers that haven't been marked beautiful in one of the previous steps, we have to find the number of skyscrapers we can visit from that skyscraper going to the left. It can be computed dynamically, in a way similar to step 2. Analogously, the number of skyscrapers visitable to the right can be computed similarly to step 3.
  5. The final length of the longest non-beautiful sequence is simply the largest of the numbers obtained in step 4.

The complexity of the algorithm is \mathcal O(N) in both cases.


Comments

There are no comments at the moment.