Editorial for DMOPC '21 Contest 5 P3 - Permutations & Primes
Submitting an official solution before solving the problem yourself is a bannable offence.
Author:
Subtask 1
First of all, let's see how we can determine who the winner is for any arbitrary permutation of heights. It turns out this is a relatively simple dynamic programming problem. If we let  if Nene-Robo starts at the building with height 
 and the player making the move wins and 
 otherwise, then we can iterate the buildings in increasing order of height to calculate higher DP states. Note that for each building we only need to consider transitioning to buildings that are a prime distance away. Since there are 
 prime numbers under 
 and 
 states to compute, this DP runs in a total of 
. This may seem scarily large, but the computational time is much smaller in practice if we break out of the transition loop as soon as we find a winning possibility.
A simple way to leverage the work above into a solution is to loop through all permutations of  in lexicographically increasing order, stopping and outputting the permutation as soon as we find one with 
. Is the time complexity of this 
? No, in fact, it is still 
 per test case! We'll see why in the next section.
Time Complexity: 
Subtask 2
Why was our previous solution so fast? If we print the answer for some values of , we will see that the answer is almost always 
. If not, it is almost always the second smallest permutation 
. If neither of these are winning for Nene, then we can prove that the next smallest permutation 
 will always be winning for Nene. There is a simple proof of this fact which will be left as an exercise to the reader. Now that we have these observations, we can instead precompute the DP array only for the identity permutation 
. After all, the set of possible moves for 
 is the exact same as the set of possible moves for 
. This allows us to determine the answer to each test case in 
 time.
Time Complexity: 
Comments
Hey I am little confused with the Editorial. We can make transition from smallest height to bigger height but we need to come at index which is not been used also right How we can keep track of that (like should we take a set for keeping that)?