Problems > Minimum Swaps to Sort

Minimum Swaps to Sort

Difficulty: 1500 3000 ms 128 MB

math sorting

The list is a permutation of 1..N. Any two elements may be swapped. What is the minimum number of swaps to sort it ascending?

Input: the first line has N; the second line has a permutation of 1..N.

Output: the minimum number of swaps.

Constraints:

  • 1 ≤ N ≤ 105

Sample Tests

Input 1
5
2 3 4 5 1
Output 1
4
Input 2
4
1 2 3 4
Output 2
0

Read the Editorial

Discussion (opens after you solve — no spoilers before)

No comments yet.

Submit Your Solution

Log in or create a free account to run and submit code.