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;
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define rep(i,n)   FOR(i,0,n)
#define pb emplace_back
typedef long long ll;
typedef pair<int,int> pint;

int a[1001],b[1001],c[10001];
bool used[1001];
int main(){
    int n;
    cin>>n;
    int mn=10001;
    rep(i,n){
        cin>>a[i];
        b[i]=a[i];
        mn=min(mn,a[i]);
    }
    sort(b,b+n);
    rep(i,n) c[b[i]]=i;
    ll ans=0;
    rep(i,n){
        if(used[i]) continue;
        ll sum=0;
        int mm=10001,cur=i,cnt=0;
        while(!used[cur]){
            used[cur]=true;
            mm=min(mm,a[cur]);
            sum+=a[cur];
            cur=c[a[cur]];++cnt;
        }
        ans+=min(sum+(cnt-2)*mm,mm+sum+(cnt+1)*mn);
    }
    cout<<ans<<endl;
    return 0;
}
