Permutation Cycles
InterviewTime limit1sMemory limit256 MB
Count the disjoint directed cycles in the permutation given in each test case.
Problem
A permutation of the N integers from 1 to N can be written down in several ways. For example, the permutation (3, 2, 7, 8, 1, 4, 5, 6) of 8 numbers is written as an array like this.
The same permutation can also be drawn as a directed graph. If the permutation is written as the array , draw an edge from to for every . Each vertex of that graph has exactly one incoming edge and one outgoing edge, so the graph splits into cycles that share no vertex. A cycle of this kind is called a permutation cycle.
The graph of the permutation (3, 2, 7, 8, 1, 4, 5, 6) has 3 permutation cycles. They are 1 → 3 → 7 → 5 → 1, 2 → 2, and 4 → 8 → 6 → 4.
Given a permutation of N integers, write a program that counts its permutation cycles.
Input
The first line contains the number of test cases T. The first line of each test case contains the size of the permutation N (2 ≤ N ≤ 1,000). The second line contains the N integers of the permutation, separated by spaces.
Output
For each test case, print the number of permutation cycles in the given permutation, one per line.