n = gets.to_i
baggage = gets.split.map(&:to_i)
sorted = baggage.sort
sorted_index = sorted.map{ |s| baggage.index(s) }
cost = 0
used = [false] * n
n.times do |s|
  next if used[s]
  cur = s
  count = 0
  loop do
    count += 1
    t = baggage.index(sorted[cur])
    used[cur] = true
    cost += baggage[cur]
    cur = sorted_index[cur]
    break if used[cur]
  end
  cost += [sorted[cur] * (count - 2), sorted[cur] + sorted[0] * (count + 1)].min
end
p cost