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>
#define INF 0x3f3f3f3f
#define DOF 0x7f7f7f7f
#define mem(a,b) memset(a,b,sizeof(a))
#define IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
typedef long long ll;
using namespace std;
const int maxn=1e5+10;

int n;
int a[maxn],b[maxn],vis[maxn];

ll solve()
{
    map<int,int>mt;
    int x=INF;
    for(int i=1;i<=n;++i)
    {
        b[i]=a[i];
        x=min(x,a[i]);
    }
    sort(b+1,b+1+n);
    for(int i=1;i<=n;++i)
        mt[b[i]]=i;
    ll ans=0;
    for(int i=1;i<=n;++i)
    {
        ll cnt=0,sum=0,minn=INF,tmp=i;
        while(1)
        {
            vis[tmp]=1;
            ++cnt;
            minn=min(minn,a[tmp]*1ll);
            sum+=a[tmp];
            tmp=mt[a[tmp]];
            if(vis[tmp]) break;


        }
        ans=ans+min(sum+(cnt-2)*minn,sum+(cnt-2)*minn+2*(minn+x)-(cnt-1)*(minn-x));
    }
    return ans;
}

int main()
{
    cin>>n;
    for(int i=1;i<=n;++i) cin>>a[i];
    ll ans=solve();
    cout<<ans<<endl;
}

