Editorial for WC '15 Contest 2 S1 - The Phantom Menace
Submitting an official solution before solving the problem yourself is a bannable offence.
Given an array  of 
 ordered integers each between 
 and 
, we must replace the 
's with other numbers between 
 and 
 such that no two adjacent numbers are the same, and that the resulting array is lexicographically smallest. You may be tempted to try some recursive solution, but this is unnecessarily complicated and may very well exceed the time limit. Instead, we can take advantage of the second requirement to construct a greedy solution.
Note that for any given  between 
 and 
 such that 
, it is always more important to minimize the value at 
 than any index greater than 
. This is because the goal is to ultimately find a solution which minimizes the lexicographical rank of the entire array, and earlier indices take precedence. Now note that it will always be possible to fill in any 
-value in the array, no matter what its neighbouring values are (at most 
 of the 
 possible values will be prohibited). This makes it so we don't have to worry about the "consequences" of our decisions – namely, whether the current choice will eventually lead to no possible way to fill in a cell later on. Putting these two observations together, we know that as long as we minimize the current value, there will always be an answer which is lexicographically smallest.
Now, we can loop through each unassigned scene in order from  to 
 and try to assign it the smallest value in the range 
 which is unequal to that of the previous scene (if any) and also unequal to that of the following scene (if it exists and is pre-assigned to a setting). We must be careful to not access the array out of bounds at the border iterations. This greedy process (implemented below) takes 
 steps, which means that it runs in 
 time.
Comments