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>
void swap(int *a, int *b) {
  int temp = *a;
  *a = *b;
  *b = temp;
  return;
}
void merge(int A[], int left, int mid, int right) {
  int n1 = mid - left;
  int n2 = right - mid;
  int L[n1 + 1], R[n2 + 1];
  int i, j, k;
  for (i = 0; i < n1; i++) {
    L[i] = A[left + i];
  }
  for (i = 0; i < n2; i++) {
    R[i] = A[mid + i];
  }
  L[n1] = INT_MAX;
  R[n2] = INT_MAX;
  i = 0;
  j = 0;
  for (k = left; k < right; k++) {
    if (L[i] <= R[j]) {
      A[k] = L[i++];
    } else {
      A[k] = R[j++];
    }
  }
  return;
}
void mergeSort(int A[], int left, int right) {
  if (left + 1 < right) {
    int mid = (left + right) / 2;
    mergeSort(A, left, mid);
    mergeSort(A, mid, right);
    merge(A, left, mid, right);
  }
  return;
}
int minimumCostSort(int A[], int sorted[], int n) {
  int i, j;
  int min, minj, target, targetj;
  int cost = 0;
  for (i = 0; i < n; i++) {
    min = sorted[i];
    for (j = 0; j < n; j++) {
      if (A[j] == min) {
        minj = j;
        break;
      }
    }
    while (minj != i) {
      target = sorted[minj];
      for (j = 0; j < n; j++) {
        if (A[j] == target) {
          targetj = j;
          break;
        }
      }
      cost += A[minj] + A[targetj];
      swap(&A[minj], &A[targetj]);
      minj = targetj;
    }
  }
  return cost;
}
int main() {
  int n, i;
  int w[1000], sorted[1000];
  scanf("%d", &n);
  for (i = 0; i < n; i++) {
    scanf("%d", &w[i]);
    sorted[i] = w[i];
  }
  mergeSort(sorted, 0, n);
  printf("%d\n", minimumCostSort(w, sorted, n));
  return 0;
}
