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>
typedef struct _node {
  int value;
  int place;
} node;
int A[1000];
int int_sort(const void *a, const void *b) {
  int p = ((node *)a)->value;
  int q = ((node *)b)->value;
  if (p < q) {
    return -1;
  } else if (p == q) {
    return 0;
  }
  return 1;
}
int sillysort(int *A, int m) {
  int s;
  int cost = 0;
  int i;
  int j;
  int n;
  int amin;
  int sum;
  int next;
  node nodes[1000] = {0};
  node temp[1000] = {0};
  for (i = 0; i < m; i++) {
    nodes[i].value = A[i];
    temp[i].value = A[i];
    temp[i].place = i;
  }
  qsort(&temp, m, sizeof(node), int_sort);
  for (i = 0; i < m; i++) {
    nodes[temp[i].place].place = i;
  }
  s = temp[0].value;
  for (i = 0; i < m; i++) {
    j = nodes[i].place;
    if (j >= 0 && j != i) {
      n = 1;
      amin = sum = nodes[i].value;
      while (j != i) {
        next = nodes[j].place;
        if (nodes[j].value < amin) {
          amin = nodes[j].value;
        }
        sum += nodes[j].value;
        n++;
        nodes[j].place = -1;
        j = next;
      }
      cost += (((sum + (n - 2) * amin) < (sum + amin + (n - 1) * s))
                   ? (sum + (n - 2) * amin)
                   : (sum + amin + (n - 1) * s));
    }
  }
  return cost;
}
int main(void) {
  int i;
  int N;
  int ans;
  scanf("%d", &N);
  for (i = 0; i < N; i++) {
    scanf("%d", &A[i]);
  }
  ans = sillysort(A, N);
  printf("%d\n", ans);
  return 0;
}
