Cow Sorting
InterviewTime limit1sMemory limit128 MB
Rearrange a permutation into sorted order by swapping any two elements at a cost equal to their sum, minimizing the total cost.
- Level
Medium7 of 10
- Topics
- Greedy, Sorting, Math, Implementation
- Solved
- No attempts yet
Problem
Farmer John's cows () are lined up to be milked in the evening. Each cow has a unique grumpiness level in the range . Since grumpy cows are more likely to damage FJ's milking equipment, FJ would like to reorder the cows in line so that they stand 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 units of time to exchange two cows whose grumpiness levels are and .
Help FJ compute the minimum total time required to reorder the cows into increasing order of grumpiness.
Input
- Line : A single integer .
- Lines : Line contains a single integer, the grumpiness of cow .
Output
- A single line with the minimum time required to reorder the cows into increasing order of grumpiness.
Hint
Suppose the cows stand in grumpiness order . First interchange the cows with grumpiness and at a cost of , giving . Then interchange the cows with grumpiness and at a cost of , giving , for a total cost of .