n = gets.chomp.to_i
t = []
arr = gets.chomp.split.map(&:to_i)
n.times do |i|
  t << arr.shift
end


def swap(list, a, b)
  list[a], list[b] = list[b], list[a]
  return list
end

def minCostPath(list)
  before = (0..list.size-1).to_a
  sorted = list.sort
  after = []
  list.each do |item|
    after << sorted.index(item) 
  end
  s = 20000
  idx1, idx2 = 0
  before.zip(after).each  do |bef,aft|
    unless bef == aft
      sum = list[bef] + list[aft]  
      if sum < s
        s = sum
        idx1 = bef
        idx2 = aft
      end
    end
  end

  return idx1, idx2, s
end

total = 0

while true
  i, j, s = minCostPath(t)
  break if s == 20000
  total += s
  t = swap(t, i,j)
end
p total