#P6193. [USACO07FEB] Cow Sorting G

[USACO07FEB] Cow Sorting G

Problem Description

Farmer John has nn cows (1n1051 \leq n \leq 10^5) standing in a line. Each cow has a “grumpiness” level in the range 11051 \ldots 10^5, and no two cows have the same grumpiness value. Since grumpier cows are more likely to damage FJ’s milking equipment, FJ wants to rearrange the cows so that they are ordered by increasing grumpiness.

During this process, the positions of any two cows (not necessarily adjacent) can be swapped. Since grumpy cows are hard to move, FJ needs a total of X+YX + Y units of time to swap two cows whose grumpiness levels are XX and YY. Please help FJ compute the minimum time needed to sort the cows in increasing order of grumpiness.

Input Format

The first line contains one integer: NN.

The next NN lines each contain one integer aia_i, representing the grumpiness value of the ii-th cow.

Output Format

Output the minimum time needed to sort all cows in increasing order of grumpiness.

3 
2 
3 
1
7

Hint

Translated by ChatGPT 5