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<iostream>
#include<algorithm>
using namespace std;
#define max 1000
#define vmax 10000
int n,A[max],allMin;
int B[max];//定义排序之后的货物
int T[vmax];//值每一个货物应该摆放的位置
int sum;//存储总成本
bool Flag[max];//标志当前货物是否被摆放到正确位置
int deal(){
int fsum=0;
for(int i=0;i<n;i++){//从0开始检索当前位置是否被摆放
    if(Flag[i]==true) continue;
    int now=i;
    int sinCirvalue=0;
    int sinMin=vmax;
    int sNum=0;
    while(1){
        Flag[now]=true;
        sNum++;
        sinMin=min(sinMin,A[now]);
        sinCirvalue+=A[now];
        now=T[A[now]];
        if(Flag[now]==true) break;
    }
    fsum+=min(sinCirvalue+(sNum-2)*sinMin,sinCirvalue+sinMin+(sNum+1)*allMin);
}
return fsum;
}
int main(){
    cin>>n;
    allMin=vmax;
    for(int i=0;i<n;i++){
    cin>>A[i];
    B[i]=A[i];
    allMin=min(allMin,A[i]);
    Flag[i]=false;
    }
    sort(B,B+n);//得到最后的排序结果
    for(int i=0;i<n;i++){
    T[B[i]]=i;//索引是货物的重量，值是这个货物应该摆放的位置
    }
    sum=deal();
    cout<<sum<<endl;
    return 0;
}

