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 C# (judge verdict: Accepted)

using System;
using System.Collections.Generic;
using System.Text;

class Program
{

    public void Proc()
    {
        this.Num = int.Parse(Console.ReadLine());
        this.NumS = VMAX;

        string[] inpt = Console.ReadLine().Split(' ');
        for(int i=0; i<this.Num;i++) {
            this.ArrA[i] = int.Parse(inpt[i]);
            this.NumS = Math.Min(this.NumS, this.ArrA[i]);
        }
        int ans = this.Solve();
        Console.WriteLine(ans);
    }

    private const int MAX = 1000;
    private const int VMAX = 10000;

    private int[] ArrA = new int[MAX];
    private int[] ArrB = new int[MAX];
    private int[] ArrT = new int[VMAX + 1];
    private int Num = 0;
    private int NumS = 0;

    private int Solve()
    {
        int ans = 0;

        bool[] arrV = new bool[MAX];
        this.ArrB = new int[this.Num];
        for(int i=0; i<this.Num; i++) {
            this.ArrB[i] = this.ArrA[i];
            arrV[i] = false;
        }
        Array.Sort(this.ArrB);
        for(int i=0; i<this.Num; i++) {
            this.ArrT[this.ArrB[i]] = i;
        }
        for(int i=0; i<this.Num; i++) {
            if(arrV[i]) {
                continue;
            }
            int cur = i;
            int S = 0;
            int m = VMAX;
            int an = 0;
            while(true) {
                arrV[cur] = true;
                an++;
                int v = this.ArrA[cur];
                m = Math.Min(m, v);
                S += v;
                cur = this.ArrT[v];
                if (arrV[cur])
                {
                    break;
                }
            }
            ans += Math.Min(S + (an - 2) * m, m + S + (an + 1) * this.NumS);
        }
        return ans;
    }


    static void Main(string[] args)
    {
        Program prg = new Program();
        prg.Proc();
    }
}