Problem 378989 · hard · Level 03 Linear Management & Searching

Rearranging the Heavy Display Stones

sorting · permutation cycles · greedy · minimum swaps

A museum shelf holds stones with distinct weights weights, left to right. A curator may swap any two stones (not only neighbours); swapping stones of weights a and b costs a + b. Return the minimum total cost to put the shelf in increasing order of weight. An empty or already sorted shelf costs 0.

Examples

Input:  weights = [5, 3, 4]
Output: 15
Explanation: swap 3 and 4 (cost 7), then 3 and 5 (cost 8), for 15 in total.
Input:  weights = [1, 11, 13, 10, 12]
Output: 61
Explanation: 11, 13, 10 and 12 form one loop. The best plan using only those four costs 66; borrowing
the 1 is cheaper: swap 1 and 10, fix the other three stones using the 1, then swap it back, 61 in total.

Constraints

  • 0 <= len(weights) <= 10**5
  • 1 <= weights[i] <= 10**6, all different
  • An O(n log n) solution is expected.

Goals

  • Split the rearrangement into independent cycles by comparing with the sorted order
  • Price each cycle two ways: with its own lightest stone, or with the lightest stone overall
  • Use a dictionary from value to sorted position instead of repeated searching
Starting Python…