gets
a = gets.split.map(&:to_i)
b = a.clone.sort

gmin = b[0]

cost = 0
loop = {}
0.upto(b.size-1){|i|
  if a[i] != b[i] && loop[i] != 1 then
    sum = 0
    min = a[i]
    n = 0
    idx = b.index(a[i])
    loop[idx] = 1
    flag = 0
    loop do
      min = a[idx] if min > a[idx]
      flag = 1 if a[idx] == gmin
      sum += a[idx]
      idx = b.index(a[idx])
#      printf "idx: %d\n", idx
      n += 1
      break if loop[idx] == 1
      loop[idx] = 1
    end
    if n == 2 then
      cost += sum
    elsif n > 2 then
      if (n-2) * min < min + (n+1)*gmin then
        cost += sum + (n-2) * min
      else
        cost += sum + min + (n+1) * gmin
      end
    end
#    printf "%d %d %d %d\n", sum, min, n, flag
  end
}

puts cost