def calc_cost cycle, min_num
  x = cycle.sum + (cycle.length - 2) * cycle.min
  y = cycle.sum + cycle.min + (cycle.length + 1) * min_num
  [x, y].min
end

n = gets.chomp.to_i
as = gets.chomp.split(' ').map(&:to_i)
min_num = as.min
bs = as.sort
cycles = []
while !as.empty?
  a = as.shift
  b = bs.shift
  next if a == b
  cs = [a, b]
  while fb = as.find_index(b)
    b = bs[fb]
    cs << b
    as.delete_at(fb)
    bs.delete_at(fb)
  end
  cycles << cs
end

cost = 0
cycles.each do |c|
  c.pop
  cost += calc_cost(c, min_num)
end
puts cost
