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>
int n;
int search(int *A, int w);
int main(int argc, char *argv[]) {
  int i, j, k, l, t;
  int *A, *R, *g, tmp, g_minj, minj, wm;
  int cost = 0;
  scanf("%d", &n);
  A = (int *)malloc(sizeof(int) * n);
  R = (int *)malloc(sizeof(int) * n);
  g = (int *)malloc(sizeof(int) * n);
  for (i = 0; i < n; i++) {
    scanf("%d", &A[i]);
    R[i] = A[i];
    g[i] = 0;
  }
  for (i = 0; i < n; i++) {
    minj = i;
    for (j = i; j < n; j++) {
      if (R[minj] > R[j]) minj = j;
    }
    tmp = R[minj];
    R[minj] = R[i];
    R[i] = tmp;
  }
  for (i = 0; i < n; i++) {
    if (A[i] == R[i]) continue;
    g_minj = i;
    g[0] = i;
    k = 1;
    j = i;
    while (A[j] != R[i]) {
      j = search(R, A[j]);
      if (A[j] < A[g_minj]) {
        g_minj = j;
        wm = A[g_minj];
      }
      g[k++] = j;
    }
    l = search(g, g_minj);
    if (k >= 3) {
      minj = search(A, R[0]);
      if (minj != g_minj) {
        cost += A[minj] + A[g_minj];
        tmp = A[minj];
        A[minj] = A[g_minj];
        A[g_minj] = tmp;
      }
      g_minj = minj;
    }
    for (j = k; j > 1; j--) {
      t = (l + j - 1) % k;
      cost += A[g[t]] + A[g[t + 1]];
      tmp = A[g[t + 1]];
      A[g[t + 1]] = A[g[t]];
      A[g[t]] = tmp;
    }
    if (k >= 3) {
      minj = search(A, R[0]);
      if (minj != g_minj) {
        cost += A[minj] + A[g_minj];
        tmp = A[g_minj];
        A[g_minj] = A[minj];
        A[minj] = tmp;
      }
    }
  }
  printf("%d\n", cost);
  return 0;
}
int search(int *A, int w) {
  int i;
  int found;
  found = 0;
  for (i = 0; i < n; i++) {
    if (A[i] == w) {
      found = 1;
      break;
    }
  }
  if (found == 1)
    return i;
  else
    return -1;
}
