eolymp
bolt
Try our new interface for solving problems
Problems

Cow Sorting

Cow Sorting

Farmer John's \textbf{N} (\textbf{1} ≤ \textbf{N} ≤ \textbf{10000}) cows are lined up to be milked in the evening. Each cow has a unique "grumpiness" level in the range \textbf{1}...\textbf{100000}. Since grumpy cows are more likely to damage FJ's milking equipment, FJ would like to reorder the cows in line so they are lined up in increasing order of grumpiness. During this process, the places of any two cows (not necessarily adjacent) can be interchanged. Since grumpy cows are harder to move, it takes FJ a total of \textbf{X}+\textbf{Y} units of time to exchange two cows whose grumpiness levels are \textbf{X} and \textbf{Y}. Please help FJ calculate the minimal time required to reorder the cows. \InputFile Line \textbf{1}: A single integer: \textbf{N}. Lines \textbf{2}..\textbf{N}+\textbf{1}: Each line contains a single integer: line \textbf{i}+\textbf{1} describes the grumpiness of cow \textbf{i}. \OutputFile Line \textbf{1}: A single line with the minimal time required to reorder the cows in increasing order of grumpiness. \textbf{Hint} \textbf{2 3 1} : Initial order. \textbf{2 1 3} : After interchanging cows with grumpiness \textbf{3} and \textbf{1} (time=\textbf{1}+\textbf{3}=\textbf{4}). \textbf{1 2 3} : After interchanging cows with grumpiness \textbf{1} and \textbf{2} (time=\textbf{2}+\textbf{1}=\textbf{3}).
Time limit 2 seconds
Memory limit 64 MiB
Input example #1
3
2
3
1
Output example #1
7