Permutations

4

6 votes
Cyclic permutation, Combinatorics, Square Of Permutation, Permutations, Easy-Medium, Mathematics, Cycles
Problem

Consider a Permutation P of length N.

Let us define an operation on P as follows:

  • P[i]=P[P[i]]      i from 1 to N.

For example

Let initially P=[2 3 1]

So, P[1]=2,P[2]=3,P[3]=1

After 1 operation:

 P[1] becomes P[P[1]]=P[2]=3

 P[2] becomes P[P[2]]=P[3]=1

 P[3] becomes P[P[3]]=P[1]=2

 So, P becomes [3 1 2]

You need to find the minimum number of operations after which P becomes an Identity Permutation.

Output 1 if not possible.

Note

  • Identity Permutation is 1,2,3N

Input Format

  • The First line contains an integer T representing the number of test cases.
  • Each test case contains an integer N representing the size of permutation P.
  • Next line contains N space seperated integers representing the permutation P.

Output Format

  • For each test case, Print the minimum number of operations as asked, output 1 if not possible.

Constraints

  • 1T5
  • 1N106
  • 1P[i]N
Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

In Sample 1, the permutation becomes Identity permutation in 1 operation.

In Sample 2, the permutation can never become an Identity permutation, hence answer is 1.

Editor Image

?