#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;

int main()
{
	int n, c = 0;
	int a[1000], b[1000];
	bool f[1000];

	cin >> n;

	for (int i = 0; i < n; i++)
		cin >> a[i];

	memcpy(b, a, sizeof(a));
	sort(b, b + n);
	memset(f, 0, sizeof(f));

	for (int i = 0; i < n; i++) {
		if (a[i] == b[i])
			f[i] = 1;
	}

	for (int i = 0; i < n; i++) {
		if (f[i] == 0){
			int s = 0;
			while (a[i] != b[i]) {
				int j = i, k = i;
				while (f[j] == 1 || a[j] != b[i])
					j++;
				while (f[k] == 1 || a[k] != b[j])
					k++;
				swap(a[j], a[k]);
				c += a[j] + a[k];
				f[j] = 1;
				s++;
			}
			if ((s - 2) * b[i] > (s + 2) * b[0])
				c -= (s - 2) * b[i] - (s + 2) * b[0];
			f[i] = 1;
		}
	}

	cout << c << endl;

	return 0;
}
