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 <vector>
#include <algorithm>
#include <map>

using namespace std;

int main(void) {
	int n;
	cin >> n;
	map<int,int> NP;
	vector<int> A(n),B(n);
	int nmin = (1 << 28);
	for (int i = 0; i < n; ++i) {
		cin >> A[i];
		B[i] = A[i];
		nmin = min(A[i],nmin);
		NP[A[i]] = i;
	}
	sort(B.begin(),B.end());
	map<int,int> TP;
	for (int i = 0; i < n; ++i) {
		TP[B[i]] = i;
	}

	int ind = 0;
	vector<int> WPN(n,0);
	for (int i = 0; i < n; ++i) {
		if (A[i] != B[i]) {
			WPN[ind] = -A[i];
			++ind;
		}
	}
	sort(WPN.begin(),WPN.end());

	int res = 0;
	for (int i = 0; WPN[i] < 0; ++i) {
		WPN[i] = -WPN[i];
		if (TP[WPN[i]] != NP[WPN[i]]) {
			int next = A[TP[WPN[i]]];
			if (TP[next] == NP[WPN[i]]) {
				res += next+WPN[i];
				NP[WPN[i]] = TP[WPN[i]];
				NP[next] = TP[next];
			}
			else {
				int nos = 0;
				int cost = WPN[i];
				int mc = (1 << 28);
				NP[WPN[i]] = TP[WPN[i]];
				while (next != WPN[i]) {
					mc = min(next,mc);
					cost += next;
					NP[next] = TP[next];
					next = A[TP[next]];
					++nos;
				}
				res += cost + min(mc*(nos-1),(nmin*nos)+(2*nmin)+mc);
			}
		}
	}
	cout << res << endl;

	return 0;
}

