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;
const int MAX_W = 10000;
void writeVector(vector<int>& v) {
  for (int i = 0; i < v.size(); i++) {
    cout << v.at(i) << "\n";
  }
}
void writeVector(vector<bool>& v) {
  for (int i = 0; i < v.size(); i++) {
    cout << v.at(i) << "\n";
  }
}
int main() {
  int n, input, min_all = MAX_W, total_sum = 0;
  cin >> n;
  vector<int> v, inv_v(MAX_W);
  vector<bool> isIterated(n);
  for (int i = 0; i < isIterated.size(); i++) {
    isIterated.at(i) = false;
  }
  for (int i = 0; i < n; i++) {
    cin >> input;
    v.push_back(input);
    inv_v.at(input) = i;
    if (input < min_all) {
      min_all = input;
    }
  }
  sort(v.begin(), v.end());
  for (int i = 0; i < v.size(); i++) {
    int min_in_loop = MAX_W;
    int sum_loop = 0;
    int pos = i;
    int elem = v.at(i);
    int loop_size = 0;
    if (not isIterated.at(pos)) {
      isIterated.at(pos) = true;
      if (inv_v.at(v.at(pos)) == pos) {
        continue;
      }
      while (true) {
        loop_size++;
        isIterated.at(pos) = true;
        sum_loop += elem;
        if (elem < min_in_loop) {
          min_in_loop = elem;
        }
        pos = inv_v.at(elem);
        elem = v.at(pos);
        if (isIterated.at(pos)) {
          int add = min(min_in_loop * (loop_size - 2), min_all * (loop_size));
          total_sum += sum_loop + add;
          break;
        }
      }
    }
  }
  cout << total_sum << "\n";
  return 0;
}
