object Main extends App {
  val _ = io.StdIn.readInt()
  val arr: Array[Int] = io.StdIn.readLine().split(" ").map(_.toInt)
  val min = arr.min

  def mkGroup(s: IndexedSeq[Int]): Seq[Seq[Int]] = {
    val sorted: Seq[Int] = s.sorted
    val m: collection.mutable.Map[Int, Int] = collection.mutable.Map.empty
    s.indices.foreach(i => m.update(i, sorted.indexOf(s(i))))
    def getCycle(n: Int): List[Int] = m.get(n) match {
      case None => List()
      case Some(x) => m.remove(n); n :: getCycle(x)
    }
    s.indices.map(i => getCycle(i)).filterNot(_.isEmpty)
  }

  def cost(inds: Seq[Int]): Int = {
    val s = inds.map(arr(_))
    ((s.length - 2) * s.min + s.sum).min((s.length+1) * min + s.min + s.sum)
  }

  val groups = mkGroup(arr)
  println((groups map cost).sum)
}