Problem 312
Minimum Swaps to Sort
Medium · 20 pts · Array, Sorting, Graph
Problem
An array contains N distinct integers. In one move you may swap any two elements (they do not have to be neighbours). Find the minimum number of swaps needed to sort the array in ascending order. Hint: look at where each element has to go; the positions form cycles, and a cycle of length L needs exactly L - 1 swaps.
Input
The first line contains an integer N, the size of the array. The second line contains N space-separated integers A[0], A[1], ..., A[N-1]. All values are distinct.
Output
Print the minimum number of swaps.
Constraints
1 <= N <= 100000; -1000000000 <= A[i] <= 1000000000; values are distinct
Example input
4 4 3 2 1
Example output
2
Explanation
In 4 3 2 1, swapping 4 with 1 gives 1 3 2 4, and swapping 3 with 2 gives 1 2 3 4. Two swaps are needed, and one swap cannot sort it.