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 cost = 0;
int SortCost(int A[], int n, int min) {
  int i;
  for (i = 0; i <= n - 1; i++) {
    if (A[i] != min) cost += A[i] + min;
  }
}
int partition(int A[], int p, int r) {
  int i, j;
  int x, temp;
  x = A[r];
  i = p - 1;
  for (j = p; j <= r - 1; j++) {
    if (A[j] <= x) {
      i++;
      temp = A[j];
      A[j] = A[i];
      A[i] = temp;
    }
  }
  temp = A[r];
  A[r] = A[i + 1];
  A[i + 1] = temp;
  return i + 1;
}
int 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 bs(int A[], int n, int c) {
  int j, k, l;
  j = 0;
  k = n - 1;
  while (1) {
    if (j <= k) {
      l = (j + k) / 2;
      if (A[l] > c) {
        k = l - 1;
      } else if (A[l] < c) {
        j = l + 1;
      } else {
        return l;
      }
    }
  }
}
int main() {
  int i, j, n, k;
  int A[1000];
  int B[1000];
  int S[1000];
  int a[1000];
  scanf("%d", &n);
  for (i = 0; i <= n - 1; i++) {
    scanf("%d", &A[i]);
    S[i] = A[i];
    a[i] = 0;
  }
  quickSort(S, 0, n - 1);
  for (i = 0; i <= n - 1; i++) {
    j = 0;
    if (a[i] == 0 && A[i] != S[i]) {
      B[j] = A[i];
      j++;
      do {
        k = bs(S, n, B[j - 1]);
        B[j] = A[k];
        a[k] = 1;
        j++;
      } while (B[j - 1] != B[0]);
      SortCost(B, j - 1, S[i]);
    }
  }
  printf("%d\n", cost);
  return 0;
}
