#P1327. Minimum Swaps to Sort

    ID: 14614 Type: Default 1000ms 256MiB

Minimum Swaps to Sort

Minimum Swaps to Sort

You are given a sequence \(a\) of distinct integers, i.e. \(a_i \neq a_j\) for all \(i \neq j\). Your task is to sort the sequence in ascending order. In one move, you are allowed to swap any two elements of the sequence.

Determine the minimum number of swaps required to sort the sequence.

Hint: The optimal strategy involves decomposing the permutation into cycles and using the formula \(\text{swaps} = \sum (\text{cycle length} - 1)\).

inputFormat

The first line contains an integer \(n\) representing the number of elements in the sequence. The second line contains \(n\) space-separated integers which are all distinct.

outputFormat

Output a single integer denoting the minimum number of swaps required to sort the sequence in ascending order.

sample

3
3 1 2
1