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;
int partition(int *A, int p, int r) {
  int j, x, temp;
  x = A[r];
  j = p - 1;
  for (int i = p; i < r; i++) {
    if (A[i] <= x) {
      j++;
      temp = A[i];
      A[i] = A[j];
      A[j] = temp;
    }
  }
  temp = A[j + 1];
  A[j + 1] = A[r];
  A[r] = temp;
  return j + 1;
}
void quicksort(int *A, int p, int r) {
  int q;
  if (p < r) {
    q = partition(A, p, r);
    quicksort(A, p, q - 1);
    quicksort(A, q + 1, r);
  }
}
int main() {
  bool check;
  int n, a[1000] = {0}, b[1000] = {0};
  int sum1 = 0, sum2 = 0, pivot = 0, pivot1 = 0, pivot2 = 0, min = 0, start,
      temp, k;
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%d", &a[i]);
    b[i] = a[i];
  }
  quicksort(b, 0, n - 1);
  for (int i = 0; i < n; i++) {
    if (a[i] != b[i]) {
      for (int j = i + 1; j < n; j++) {
        if (b[j] == a[i] && b[i] == a[j]) {
          temp = a[i];
          a[i] = a[j];
          a[j] = temp;
          sum1 += a[i] + a[j];
        }
      }
    }
  }
  sum2 = sum1;
  for (int i = 0; i < n; i++) {
    if (a[i] != b[i]) {
      if (i == 0) {
        check = true;
      }
      start = i;
      min = a[i];
      for (int j = i + 1; j < n; j++) {
        if (min > a[j]) {
          min = a[j];
          pivot = j;
          pivot1 = pivot;
          pivot2 = pivot;
        }
      }
      break;
    }
    if (i == n - 1) {
      printf("%d\n", sum1);
      return 0;
    }
  }
  for (int i = 1; i < n - start; i++) {
    k = start;
    while (1) {
      if (b[pivot1] == a[k]) {
        temp = a[pivot1];
        a[pivot1] = a[k];
        a[k] = temp;
        sum1 += a[pivot1] + a[k];
        pivot1 = k;
        break;
      }
      k++;
    }
  }
  if (!check) {
    temp = a[pivot2];
    a[pivot2] = a[0];
    a[0] = temp;
    for (int i = 1; i < n - start; i++) {
      int j = start;
      while (1) {
        if (b[pivot2] == a[j]) {
          temp = a[pivot2];
          a[pivot2] = a[j];
          a[j] = temp;
          sum2 += a[pivot2] + a[j];
          pivot2 = j;
          break;
        }
        j++;
      }
    }
    if (sum1 < sum2) {
      printf("%d\n", sum1);
    } else {
      printf("%d\n", sum2);
    }
  }
  printf("%d\n", sum1);
  return 0;
}
