#K14096. Minimum Swaps to Sort Array
Minimum Swaps to Sort Array
Minimum Swaps to Sort Array
You are given an array of n distinct integers which represents a permutation of numbers from 1 to n in arbitrary order. Your task is to determine the minimum number of swaps required to sort the array in ascending order. In other words, you must compute the smallest number of swap operations required to change the given permutation into the sorted permutation [1,2,...,n].
Hint: The problem can be solved by detecting cycles in the permutation. If a cycle has a length of \( k \), then \( k-1 \) swaps are needed to correct that cycle.
inputFormat
The input is given via standard input (stdin). The first line contains an integer n (the size of the array). The second line contains n space-separated distinct integers representing the array.
Example:
5 4 3 2 5 1
outputFormat
Output a single integer, which is the minimum number of swaps required to sort the array in ascending order. The answer should be written to standard output (stdout).
Example:
3## sample
5
4 3 2 5 1
3
</p>