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 fordebug int hoge;cin>>hoge;
#define DEKAI 1000000007;
#define INF 200000000
#define int long long
#define lp(i,n) for(int i=0;i<n;i++)
#define lps(i,j,n) for(int i=j;i<n;i++)
pair<int,char> a[100000],b[100000];
pair<int,char> rr[100000],ll[100000];

signed main(){
	int n;
	cin>>n;
	int a[1000],b[1000];
	int mini=INF;
	lp(i,n){
		cin>>a[i];
		b[i]=a[i];
		mini=min(mini,a[i]);
	}
	sort(b,b+n);
	int x[100000];
	lp(i,n){
		x[b[i]]=i;
	}
	int ans=0;
	bool done[1000]={false};
	lp(i,n){
		if(done[i]||a[i]==b[i]) continue;
		int sum=0,mini2=INF;
		int count=0;
		int j=i;
		while(!done[j]){
			mini2=min(mini2,a[j]);
			sum+=a[j];
			done[j]=true;
			j=x[a[j]];
			count++;
		}
		int memo=sum;
		sum=sum-mini2+mini2*(count-1);
		memo=memo+mini2+mini*2+mini*(count-1);
		ans+=min(sum,memo);
	}
	cout<<ans<<endl;
	return 0;
}
