Let A[0], A[1], ..., A[N-1] be a permutation containing every integer from 0 to N-1 exactly once. From A, define a child array B of the same length as follows.
- B[0] = 0
- B[i] = A[B[i-1]] (1 <= i <= N-1)
If the child array B produced by this process is also a permutation containing every integer from 0 to N-1 exactly once, then A is called a perfect permutation.
The following table shows every permutation A of length 3 and its child array B. The permutations {1, 2, 0} and {2, 0, 1} are perfect permutations because their child arrays are also permutations.
You are given a permutation P of length N. Find a perfect permutation Q whose difference from P is as small as possible. The difference between two permutations P and Q is the number of indices i such that P[i] and Q[i] are different.