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;
pair<long long, char> a[100000], b[100000];
pair<long long, char> rr[100000], ll[100000];
signed main() {
  long long n;
  cin >> n;
  long long a[1000], b[1000];
  long long mini = 200000000;
  for (long long i = 0; i < n; i++) {
    cin >> a[i];
    b[i] = a[i];
    mini = min(mini, a[i]);
  }
  sort(b, b + n);
  long long x[100000];
  for (long long i = 0; i < n; i++) {
    x[b[i]] = i;
  }
  long long ans = 0;
  bool done[1000] = {false};
  for (long long i = 0; i < n; i++) {
    if (done[i] || a[i] == b[i]) continue;
    long long sum = 0, mini2 = 200000000;
    long long count = 0;
    long long j = i;
    while (!done[j]) {
      mini2 = min(mini2, a[j]);
      sum += a[j];
      done[j] = true;
      j = x[a[j]];
      count++;
    }
    long long 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;
}
