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.

Constraints

* $1 \leq n \leq 1,000$
* $0 \leq w_i\leq 10^4$
* $w_i$ are all different

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.

Examples

Input

5
1 5 3 4 2


Output

7


Input

4
4 3 2 1


Output

10
#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

int n,mi;
vector<int> w;

int solve(){

    int ret = 0;
    vector<int> sub(w);
    sort(sub.begin(),sub.end());
    vector<int> cir(10001);
    vector<bool> bol(n);

    for(int i=0;i<n;i++){
        cir[sub[i]] = i;
        bol[i]=false;
    }
    for(int i=0;i<n;i++){
        int sum=0,sn=0;
        int loc=i;
        int mmi=1e9;

        for(;;){
            bol[loc]=true;
            sn++;
            mmi=min(w[loc],mmi);
            sum+=w[loc];
            loc=cir[w[loc]];
            if(bol[loc])break;
        }
        ret+=min(sum+(sn-2)*mmi,sum+mmi+mi*(sn+1));
    }
    return ret;
}


int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cin >> n;
    mi = 1e9;
    for(int i=0;i<n;i++){
        int a;
        cin >> a;
        mi = min(mi,a);
        w.push_back(a);
    }
    int ans = solve();
    cout << ans << endl;
}

