n = gets.to_i
w = gets.split.map(&:to_i)
ws = w.sort
pos = {}
(0...n).each do |i|
  pos[ws[i]] = i
end
min = ws[0]
flag = [true]*n
cost = 0
(0...n).each do |i|
  if flag[i]
    flag[i] = false
    count = 0
    startPos = i
    nextPos = pos[w[i]]
    while nextPos != startPos do
      flag[nextPos] = false
      cost += ws[nextPos]
      count += 1
      nextPos = pos[w[nextPos]]
    end
    if min*count + 2*(min+ws[i]) < ws[i]*count
      cost += min*count + 2*(min+ws[i])
    else
      cost += ws[i]*count
    end
  end
end
printf("%d\n",cost)
