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;
struct weight {
  int val;
  int id;
  weight() {
    val = 0;
    id = 0;
  }
  weight(weight *w) {
    val = w->val;
    id = w->id;
  }
  void set(weight *w) {
    val = w->val;
    id = w->id;
  }
};
void merge_sort(weight *array, int left, int right);
void merge(weight *array, int left, int mid, int right);
void swap_id(weight *a, weight *b);
int cal_min_swap(weight *original, weight *sorted, int num);
int main() {
  int n;
  cin >> n;
  weight *original = (weight *)malloc(n * sizeof(weight));
  weight *sorted = (weight *)malloc(n * sizeof(weight));
  int result = 0;
  if (n < 1) {
    return 0;
  }
  for (int i = 0; i < n; i++) {
    cin >> original[i].val;
    original[i].id = i;
    sorted[i].set(&original[i]);
  }
  merge_sort(sorted, 0, n);
  cout << cal_min_swap(sorted, sorted, n) << endl;
  return 0;
}
void merge_sort(weight *array, int left, int right) {
  if (left + 1 < right) {
    int mid = (left + right) >> 1;
    merge_sort(array, mid, right);
    merge_sort(array, left, mid);
    merge(array, left, mid, right);
  }
}
void merge(weight *array, int left, int mid, int right) {
  int n1 = mid - left;
  int n2 = right - mid;
  weight *L = (weight *)malloc((n1 + 1) * sizeof(weight));
  weight *R = (weight *)malloc((n2 + 1) * sizeof(weight));
  for (int i = 0; i < n1; ++i) {
    L[i].set(&array[left + i]);
  }
  L[n1].val = INT_MAX;
  for (int i = 0; i < n2; ++i) {
    R[i].set(&array[mid + i]);
  }
  R[n2].val = INT_MAX;
  int i = 0;
  int j = 0;
  for (int k = left; k < right; ++k) {
    if (L[i].val <= R[j].val) {
      array[k].set(&L[i]);
      ++i;
    } else {
      array[k].set(&R[j]);
      ++j;
    }
  }
}
void swap_id(weight *a, weight *b) {
  int temp = b->id;
  b->id = a->id;
  a->id = temp;
}
int cal_min_swap(weight *original, weight *sorted, int num) {
  int total_swap_w = 0;
  for (int i = 0; i < num; ++i) {
    if (i != sorted[i].id) {
      total_swap_w += sorted[i].val + original[sorted[i].id].val;
      swap_id(&sorted[i], &sorted[sorted[i].id]);
      --i;
    }
  }
  return total_swap_w;
}
