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;
constexpr int MAX_N = 1000;
constexpr int MAX_VAL = 10001;
int merge(int* A, const int& left, const int& mid, const int& right) {
  const int n1 = mid - left;
  const int n2 = right - mid;
  auto L = new int[n1 + 1];
  auto R = new int[n2 + 1];
  for (int i = 0; i < n1; i++) {
    L[i] = A[left + i];
  }
  for (int i = 0; i < n2; i++) {
    R[i] = A[mid + i];
  }
  L[n1] = MAX_VAL;
  R[n2] = MAX_VAL;
  int i = 0, j = 0;
  for (int k = left; k < right; k++) {
    if (L[i] <= R[j]) {
      A[k] = L[i];
      i++;
    } else {
      A[k] = R[j];
      j++;
    }
  }
  delete[] L;
  delete[] R;
  return right - left;
}
int mergeSort(int* A, const int& left, const int& right) {
  int count = 0;
  if (left + 1 < right) {
    const int mid = (left + right) / 2;
    count += mergeSort(A, left, mid);
    count += mergeSort(A, mid, right);
    return count + merge(A, left, mid, right);
  }
  return 0;
}
int minCostSort(int* w, int* ref, int n) {
  int fixed = 0;
  for (int i = 0; i < n; i++) {
    if (w[i] == ref[i]) {
      w[i] = MAX_VAL;
      ++fixed;
    }
  }
  int cost = 0;
  while (fixed < n) {
    int* minelm = min_element(w, w + n);
    int minelm_dest = distance(ref, lower_bound(ref, ref + n, *minelm));
    int repl_dest = distance(w, minelm);
    int* repl = lower_bound(w, w + n, ref[repl_dest]);
    cost += *repl + *minelm;
    *repl = *minelm;
    *minelm = MAX_VAL;
    ++fixed;
    if (distance(w, repl) == minelm_dest) {
      *repl = MAX_VAL;
      ++fixed;
    }
  }
  return cost;
}
int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  int w[MAX_N];
  int ref[MAX_N];
  int n;
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> w[i];
    ref[i] = w[i];
  }
  sort(ref, ref + n);
  int cost = minCostSort(w, ref, n);
  cout << cost << endl;
  return 0;
}
