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>
const int MAX_N = 1000;
void print_array(std::vector<int> *A, int left, int right) {
  for (int i = left; i <= right; i++) {
    std::cout << A->at(i) << " ";
  }
  std::cout << std::endl;
}
long swap(std::vector<int> *A, int i, int j) {
  int tmp = A->at(i);
  A->at(i) = A->at(j);
  A->at(j) = tmp;
  return A->at(i) + A->at(j);
}
long sort(std::vector<int> *A, std::vector<int> *B) {
  long cost = 0;
  for (int i = 0; i < B->size(); i++) {
    int v = B->at(i);
    for (int j = i; j < A->size(); j++) {
      if (A->at(j) != v) {
        continue;
      }
      if ((A->at(j) == v) && (i == j)) {
        continue;
      } else {
        cost += swap(A, i, j);
      }
    }
  }
  return cost;
}
int partition(std::vector<int> *A, int p, int r) {
  int x = A->at(r);
  int i = p - 1;
  for (int j = p; j <= r - 1; j++) {
    if (A->at(j) <= x) {
      i++;
      swap(A, i, j);
    }
  }
  swap(A, i + 1, r);
  return i + 1;
}
void quick_sort(std::vector<int> *A, int p, int r) {
  if (p < r) {
    int q = partition(A, p, r);
    quick_sort(A, p, q - 1);
    quick_sort(A, q + 1, r);
  }
}
int main(void) {
  std::ios_base::sync_with_stdio(false);
  int n = 0;
  std::cin >> n;
  std::vector<int> *A = new std::vector<int>();
  A->reserve(MAX_N);
  for (int i = 0; i < n; i++) {
    int v = 0;
    std::cin >> v;
    A->push_back(v);
  }
  std::vector<int> *B = new std::vector<int>();
  for (int i = 0; i < A->size(); i++) {
    B->push_back(A->at(i));
  }
  quick_sort(B, 0, A->size() - 1);
  long weight = sort(A, B);
  std::cout << weight << std::endl;
  return 0;
}
