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 SelectionSort(int *array, int N) {
  int i, j, maxj, tmp, ans;
  ans = 0;
  for (i = N - 1; i >= 0; i--) {
    maxj = i;
    for (j = i; j >= 0; j--) {
      maxj = array[j] > array[maxj] ? j : maxj;
    }
    if (i != maxj) {
      ans += (array[maxj] + array[i]);
      tmp = array[maxj];
      array[maxj] = array[i];
      array[i] = tmp;
    }
  }
  return ans;
}
int partition(int *A, int left, int right) {
  int pivot = A[right];
  int i = left - 1;
  int j;
  int tmp;
  for (j = left; j < right; j++) {
    if (A[j] <= pivot) {
      i = i + 1;
      tmp = A[i];
      A[i] = A[j];
      A[j] = tmp;
    }
  }
  tmp = A[i + 1];
  A[i + 1] = A[right];
  A[right] = tmp;
  return i + 1;
}
void quicksort(int *A, int left, int right) {
  int q;
  if (left < right) {
    q = partition(A, left, right);
    quicksort(A, left, q - 1);
    quicksort(A, q + 1, right);
  }
}
void minimumCostSort(int *A, int n) {}
int arraycmp(int *A, int *B, int n) {
  int i, rtn = 0;
  for (i = 0; i < n; i++) {
    if (A[i] != B[i]) {
      rtn++;
    }
  }
  return rtn;
}
void mkarray(int *A, int *B, int n, int *C) {
  int i;
  int j = 0;
  for (i = 0; i < n; i++) {
    if (A[i] != B[i]) {
      C[j] = A[i];
      j++;
    }
  }
}
int main() {
  int n, m, i, *A, *B, *C, ans;
  A = (int *)malloc(sizeof(int) * n);
  B = (int *)malloc(sizeof(int) * n);
  scanf("%d", &n);
  for (i = 0; i < n; i++) {
    scanf("%d", &A[i]);
  }
  memcpy(B, A, sizeof(int) * n);
  quicksort(B, 0, n - 1);
  m = arraycmp(A, B, n);
  if (m == 0) {
    printf("0\n");
    return 0;
  }
  C = (int *)malloc(sizeof(int) * m);
  mkarray(A, B, n, C);
  ans = SelectionSort(C, m);
  printf("%d\n", ans);
  free(A);
  free(B);
  free(C);
  return 0;
}
