#K86312. Minimum Swaps to Sort

    ID: 36837 Type: Default 1000ms 256MiB

Minimum Swaps to Sort

Minimum Swaps to Sort

Given an array of integers, your task is to determine the minimum number of swaps required to sort the array in non-decreasing order.

The idea is based on finding cycles in the permutation of indices. For each cycle of length \(k\), the number of swaps needed is \(k - 1\). For example, if a cycle has 3 elements, you need 2 swaps to correct it.

Note: The array may contain duplicate elements, and swapping any two elements is allowed.

inputFormat

The input is given via standard input (stdin) and consists of two lines:

  • The first line contains an integer \(N\) representing the number of elements in the array.
  • The second line contains \(N\) space-separated integers.

outputFormat

Output a single integer to standard output (stdout): the minimum number of swaps required to sort the array in non-decreasing order.

## sample
5
3 1 2 5 4
3