Editorial for WC '16 Contest 3 J2 - Pokéwarehouses


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.

The most important thing to observe about this problem is that no more than 2 intermediate warehouses are ever required. To show this, we can consider the following simple algorithm which always successfully completes the shipment given 2 intermediate warehouses: repeatedly find the next item i which must be delivered to the destination warehouse, move each of the items above i to another warehouse (there will always be at least one other warehouse which they can be moved to), and then move i to the destination warehouse.

Given this insight, we've reduced the problem to just determining whether 0 intermediate warehouses are sufficient, or if not, then whether 1 intermediate warehouse is sufficient. Otherwise, the answer must be 2.

Determining whether 0 intermediate warehouses are sufficient is trivial. In this situation, there are no choices regarding how the items may be moved, and the initial order of the items must be S = [N, N-1, \dots, 1] in order for the shipment to work out.

Determining whether 1 intermediate warehouse is sufficient can be done by simulating the process, as there are similarly very few choices to be made regarding how the items should be moved. We can repeatedly apply the following greedy logic: if the next item i which must be delivered to the destination warehouse is currently on top of either of the other stacks, then move it to the destination warehouse, otherwise the only valid move is to move the top item from the initial warehouse to the intermediate warehouse (and if the initial warehouse is already empty, then there are no valid moves and the shipment can't be completed successfully).

The time complexity of this simulation is \mathcal O(N), as an item will be moved at each step, and each item will be moved at most twice in total.


Comments

There are no comments at the moment.