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 <algorithm>
#include <cstdio>

static const size_t n_max = 1000;
static std::pair<int, size_t> A[n_max];
static size_t C[n_max];
static bool visited[n_max];

int main() {
  size_t n;
  scanf("%zu\n", &n);
  for (size_t i = 0; i < n; i++) {
    scanf("%d", &A[i].first);
    A[i].second = i;
  }
  std::sort(A, A + n);
  int M = A[0].first;
  int cost = 0;
  for (size_t i = 0; i < n; i++) {
    if (visited[i])
      continue;
    visited[i] = true;
    C[0] = i;
    size_t l = 1;
    auto m = A[i].first, s = A[i].first;
    while (!visited[A[C[l-1]].second]) {
      C[l] = A[C[l-1]].second;
      visited[C[l]] = true;
      m = std::min(m, A[C[l]].first);
      s += A[C[l]].first;
      l++;
    }
    if (l == 1)
      continue;
    cost += std::min((s - m) + m * (l - 1), (s - m) + M * (l - 1) + 2 * (m + M));
  }
  printf("%d\n", cost);
  return 0;
}