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 Min(int a, int b) { return a > b ? b : a; }
void bubble_sort(int a[], int n) {
  int res = 0;
  for (int i = 0; i < n; i++) {
    for (int j = n - 1; j >= i + 1; j--) {
      if (a[j] < a[j - 1]) {
        int temp = a[j];
        a[j] = a[j - 1];
        a[j - 1] = temp;
        res++;
      }
    }
  }
}
int find(int a[], int b[], int i, int n) {
  for (int k = 0; k < n; k++) {
    if (a[i] == b[k]) return k;
  }
}
int main() {
  int n;
  scanf("%d", &n);
  int a[n + 1];
  int b[n];
  int v[n + 1];
  for (int i = 0; i < n; i++) {
    scanf("%d", &a[i]);
    b[i] = a[i];
    v[i] = 0;
  }
  bubble_sort(b, n);
  int total_cost = 0;
  int min = 10005;
  for (int i = 0; i < n; i++) {
    if (min > a[i]) min = a[i];
    int cost = 0;
    int length = 0;
    int min_cycle = 10005;
    if (v[i] == 1) continue;
    int temp = i;
    if (a[i] == b[i]) continue;
    while (a[temp] != b[i]) {
      v[temp] = 1;
      length++;
      cost += a[temp];
      if (min_cycle > a[temp]) min_cycle = a[temp];
      temp = find(a, b, temp, n);
    }
    v[temp] = 1;
    length++;
    cost += a[temp];
    if (min_cycle > a[temp]) min_cycle = a[temp];
    if (length > 2) {
      cost =
          cost + Min((length - 2) * min_cycle, min_cycle + min * (length + 1));
    }
    total_cost += cost;
  }
  printf("%d\n", total_cost);
  return 0;
}
