output_description: Print the minimal cost in a line.
input_description: In the first line, an integer $n$ is given. In the second line, $n$ integers
  $w_i (i = 0, 1, 2, ... n-1)$ separated by space characters are given.
attempt: import functools
  
  
  def find_all_rings(items):
      "items: (??°???, ?????????????????????????????????)"
      l = len(items)
      check_list = [False] * l
      rings = []
      i = 0
      while i < l:
          if check_list[i] == False:
              ring = []
              first = items[i]
              ring.append(first)
              check_list[i] = True
              item_index = first[1]
              item = items[item_index]
              while item[0] != first[0]:
                  ring.append(item)
                  check_list[item_index] = True
                  item_index = item[1]
                  item = items[item_index]
              rings.append(ring)
          i += 1
      return rings
  
  
  def compute_ring_cost(min_all, ring):
      l = len(ring)
      if l <= 1:
          return 0
      w = [item[0] for item in ring]
      min_ring = min(w)
      sum_ring = sum(w)
      if (l + 1) * min_all < (l - 3) * min_ring:
          return sum_ring + min_ring + (l + 1) * min_all
      else:
          return sum_ring + (l - 2) * min_ring
  
  
  n = int(input())
  ns = list(map(int, input().split()))
  items = []
  sorted_items = []
  for i in range(n):
      item = (ns[i], i)
      items.append(item)
      sorted_items.append(item)
  
  sorted_items.sort(key=lambda x: x[0])
  
  for i in range(n):
      item = sorted_items[i]
      items_index = item[1]
      items[items_index] = (item[0], i)
  
  rings = find_all_rings(items)
  compute_ring_cost1 = functools.partial(compute_ring_cost, min(ns))
  print(sum(map(compute_ring_cost1, rings)))
  
problem_description: Minimum Cost Sort
  
  You are given $n$ integers $w_i (i = 0, 1, ..., n-1)$ to be sorted in
  ascending order. You can swap two integers $w_i$ and $w_j$. Each swap
  operation has a cost, which is the sum of the two integers $w_i + w_j$. You
  can perform the operations any number of times.
  
  Write a program which reports the minimal total cost to sort the given
  integers.
samples: [{"input": "5\n    1 5 3 4 2", "output": "7"}, {"input": "4\n    4 3 2 1", "output": "10"}]