Editorial for Facebook Hacker Cup '15 Round 2 P1 - Lazy Sort
Submitting an official solution before solving the problem yourself is a bannable offence.
The important observation in this problem is that it becomes greedy after the first choice is made. After choosing to move the top or bottom page first, our future moves are either forced or don't matter.
Observe that, at any point, the partially completed final stack must always contain a contiguous sorted set of pages. If we had page and page touching in the final stack, there's no way we could get page in between. Let's call the minimum and maximum student IDs in the partial final stack and respectively. The only pages we can add to this stack are or . If only one of these pages is available on the top or bottom of the current unsorted pile, we must take it. If both pages are available, it doesn't matter which one we take. We can take them in either order.
That means that the only important choice is which page we grab initially, and we can of course just try both possibilities and greedily simulate the rest of the way for each. This gives us a solution that takes time and memory.
Comments