module Main where
-- import Debug.Trace
import Data.List
import qualified Data.Sequence as S
import qualified Data.ByteString.Char8 as B
import Data.Int
import Data.Char
import Data.Array
import Data.Maybe
import qualified Data.Map as M
import Data.Ord
import Data.Functor
import Control.Applicative
import Control.Monad

solve :: [Int] -> Int
solve l = iter cycles where
    iter [] = 0
    iter (c:cs) = cost c + iter cs 

    cost = iter 0 0 maxBound where
        iter c s m [] -- c: length of this cycle, s:sum of this cycle, m: minimum in this cycle.
            | c < 2 = s
            | otherwise = s + min (m*(c-2)) (ma*(c+1) + m)
        iter c s m (x:xs) = iter (c+1) (s+x) (min m x) xs

    sl = sort l
    ma = head sl  -- minimum in all
    permutation = M.fromList $ zip l sl

    cycles = iter [] l where
        iter cl [] = cl
        iter cl (x:xs)
            | elem x ul = iter cl xs
            | otherwise = iter (cycle:cl) xs where
                ul = concat cl
                cycle = iter [x] where
                    iter cl@(c:cs)
                        | v == c = [] 
                        | elem v cl = cl
                        | otherwise = iter (v:cl) where
                            v =  permutation M.! c 

readIntLn:: IO Int
readIntLn = (fst . fromJust . B.readInt) <$> B.getLine

readIntList:: IO [Int]
readIntList = map (fst . fromJust . B.readInt) . B.words <$> B.getLine

main :: IO() 
main = do
    _ <- readIntLn
    l <- readIntList

    print $ solve l 

