#C10861. Minimum Swaps to Sort

    ID: 40113 Type: Default 1000ms 256MiB

Minimum Swaps to Sort

Minimum Swaps to Sort

You are given an array of n integers. Your task is to determine the minimum number of swaps required to sort the array in non-decreasing order.

The sorting is achieved by swapping any two elements in the array. Formally, if the given array is \(a_1, a_2, \dots, a_n\), you need to determine the minimum number of swaps required to rearrange the array such that \(a_1 \le a_2 \le \dots \le a_n\).

Hint: Consider representing the array as a list of pairs (index, value) and then analyzing cycles in the permutation that maps each element's current index to its index in the sorted order. For a cycle of length \(k\), the number of swaps required is \(k-1\).

inputFormat

The input is given via stdin and has the following format:

T
n1
a1 a2 ... an1
n2
b1 b2 ... bn2
...
nT
z1 z2 ... znT

Here, T is the number of test cases. For each test case, the first line contains an integer n representing the number of elements in the array, and the second line contains n space-separated integers.

outputFormat

For each test case, output via stdout the minimum number of swaps required to sort the given array. Each result should be printed on a new line.

## sample
4
5
2 3 1 5 4
3
3 1 2
4
4 3 2 1
6
1 3 5 2 4 6
3

2 2 3

</p>