Problem:
MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Minimum Cost Sort

You are given $n$ integers $w_i (i = 0, 1, ..., n-1)$ to be sorted in ascending order. You can swap two integers $w_i$ and $w_j$. Each swap operation has a cost, which is the sum of the two integers $w_i + w_j$. You can perform the operations any number of times.

Write a program which reports the minimal total cost to sort the given integers.

Input

In the first line, an integer $n$ is given. In the second line, $n$ integers $w_i (i = 0, 1, 2, ... n-1)$ separated by space characters are given.

Output

Print the minimal cost in a line.

Constraints

$1 \leq n \leq 1,000$

$0 \leq w_i\leq 10^4$

$w_i$ are all different

Sample Input 1

5
1 5 3 4 2

Sample Output 1

7

Sample Input 2

4
4 3 2 1

Sample Output 2

10

Solution in Scala (judge verdict: Accepted)

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

object Main {
  val t = new Array[Int](10001)

  def getMin(x:Int,y:Int) = if(x<y) x else y

  def scan(a:Array[Int], used:Array[Boolean],i:Int, size:Int, min:Int, sum:Int):(Int,Int,Int) = {
    if(used(i)) (size,sum,min)
    else {
      used(i) = true
      val w = a(i)
      scan(a, used, t(w), size+1, getMin(min, w), sum+w)
    }
  }

  def getCost(a:Array[Int],min:Int,n:Int) = {
    var ans = 0
    val used = (0 until a.length).map(_=>false).toArray
    val b = a.sorted.clone

    (0 until n).foreach{ i => t(b(i))=i }

    for(i<-0 until n) {
      if(!used(i)) {
        val (size, s, m) = scan(a,used,i,0,10000,0)
        ans += getMin(s+(size-2)*m, m+s+(size+1)*min)
      }
    }
    ans
  }

  def main(args:Array[String]) = {
    val n = readInt
    val a = readLine.split(" ").map(_.toInt)
    val min = a.min
    println(getCost(a,min,n))
  }
}