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<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<climits>
#include<iostream>
#include<sstream>
#include<utility>
#include<map>
#include<vector>
#include<queue>
#include<algorithm>
#include<set>
#include<stack>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;

int N,C[1005],c=0,t,p,cost=0;
long long res=0;
map<int,int>H;//number2order
map<int,int>rH;//order2number
P nodes[1005],tmp[1005];

int main()
{
	scanf("%d",&N);
	for(int i=0;i<N;i++)
		scanf("%d",C+i);
	for(int i=0;i<N;i++)
	{
		tmp[i].first=C[i];
		tmp[i].second=i;
	}
	sort(tmp,tmp+N);
	for(int i=0;i<N;i++)
	{
		nodes[i].first=C[i];
		nodes[tmp[i].second].second=i;
	}
	int s=tmp[0].first;
	for(int i=0;i<N;i++)
	{
		int j=nodes[i].second;
		if(j>=0&&j!=1)
		{
			int n=1,amin,sum;
			amin=sum=nodes[i].first;
			while(j!=i)
			{
				int next=nodes[j].second;
				if(nodes[j].second<amin)
					amin=nodes[j].first;
				sum+=nodes[j].first;
				n++;
				nodes[j].second=-1;
				j=next;
			}
			cost+=min(sum+(n-2)*amin,sum+amin+(n+1)*s);
		}
	}
	printf("%d\n",cost);
	return 0;
}