Under construction

Still being built. Things may change

Permutation Cycles

Interview

Time limit1sMemory limit256 MB

Summary
Count the disjoint directed cycles in the permutation given in each test case.
Level

Easy3 of 10

Topics
Graph, DFS
Solved
No attempts yet

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.

(1234567832781456)\begin{pmatrix} 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 \\ 3 & 2 & 7 & 8 & 1 & 4 & 5 & 6 \end{pmatrix}

The same permutation can also be drawn as a directed graph. If the permutation is written as the array (1…i…nπ1…πi…πn)\begin{pmatrix} 1 & \dots & i & \dots & n \\ \pi_1 & \dots & \pi_i & \dots & \pi_n \end{pmatrix}, draw an edge from ii to πi\pi_i for every ii. 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.

Examples3

  1. Example 1

    Input
    2
    8
    3 2 7 8 1 4 5 6
    10
    2 1 3 4 5 6 7 9 10 8
    
    Expected output
    3
    7
    
  2. Example 2

    Input
    2
    2
    1 2
    2
    2 1
    
    Expected output
    2
    1
    
  3. Example 3

    Input
    3
    3
    2 3 1
    3
    3 1 2
    3
    1 3 2
    
    Expected output
    1
    1
    2