Let A be a permutation that contains every integer from 0 to N-1 exactly once. From A, define an array B of the same length as follows.
- B[0] = 0
- B[i] = A[B[i-1]] (1 ≤ i ≤ N-1)
If the resulting B is also a permutation, then A is called a perfect permutation.
The table below shows every permutation A of length 3 and its child array B. The permutations {1, 2, 0} and {2, 0, 1} are perfect because their child arrays are also permutations.
Given a permutation P of length N, output a perfect permutation Q whose difference from P is as small as possible. The difference between P and Q is the number of indices i for which P[i] and Q[i] are different.