import scala.io.StdIn.{readInt, readLine}

object Main extends App {
  import Solver.solve

  val n   = readInt()
  val xs  = readLine().split(' ').map { _.toInt }
  val ans = solve(xs, n)
  println(ans)
}

object Solver {
  val VMAX: Int = 10000

  def solve(xs: Array[Int], n: Int): Int = {
    val ys   = xs.sorted
    val minV = ys.head
    val zs   = Array.fill(n)(false)
    val ts = {
      val ts = new Array[Int](VMAX + 1)
      var i  = 0
      while (i < n) {
        ts(ys(i)) = i
        i += 1
      }
      ts
    }

    var ans, i = 0
    while (i < n) {
      if (!zs(i)) {
        var cur   = i
        var m     = VMAX
        var s, an = 0
        do {
          zs(cur) = true
          an += 1
          val v = xs(cur)
          m = math.min(m, v)
          s += v
          cur = ts(v)
        } while (!zs(cur))
        ans += math.min(s + (an - 2) * m, m + s + (an + 1) * minV)
      }
      i += 1
    }

    ans
  }
}

