N = gets.to_i
A = gets.split.map &:to_i
min = A.min
sorted = Array.new(N, false)
sortedA = A.sort
cost=0

A.each_with_index {|e, i|
    index = sortedA.index(e)
    next if sorted[i] or index == i
    sorted[i] = true
    sum = e
    cycleMin = e
    num = 1
    value = e
    until index == i
        sorted[index] = true
        num+=1
        value = A[index]
        sum += value
        if value < cycleMin
            cycleMin = value
        end
        index = sortedA.index(A[index])
    end
    cost1 = cycleMin * (num - 3)
    cost2 = min * (num + 1)
    cost += sum + cycleMin + (cost1<=cost2 ? cost1 : cost2)
}
puts cost