#include <bits/stdc++.h>
using namespace std;

#define VMAX 10000

int main()
{
	int n;
	cin >> n;
	vector<int> w( n );
	vector<int> b( n );
	int s = VMAX;
	for( int i = 0; i < n; i++ ) {
		cin >> w[i];
		s = min( s, w[i] );
		b[i] = w[i];
	}

	vector<bool> V( n );
	vector<int> T( VMAX + 1 );
	sort( b.begin(), b.end() );
	for( int i = 0; i < n; i++ ) {
		T[ b[i] ] = i;
	}
	int ans = 0;
	for( int i = 0; i < n; i++ ) {
		if( V[i] ) continue;
		int cur = i;
		int S = 0;
		int m = VMAX;
		int an = 0;
		while( 1 ) {
			V[cur] = true;
			an++;
			int v = w[cur];
			m = min( m, v );
			S += v;
			cur = T[v];
			if( V[cur] ) break;
		}
		ans += min( S + (an - 2)*m, m + S + (an + 1)*s );
	}

	cout << ans << endl;
}

