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;
int solve(int n, vector<int>& ws);
int main() {
  int n = 0;
  cin >> n;
  vector<int> ws(n);
  for (auto& w : ws) cin >> w;
  cout << solve(n, ws) << endl;
  return 0;
}
int solve(int n, vector<int>& ws) {
  vector<int> i2w;
  int w2i[10001] = {0};
  for (auto w : ws) w2i[w] = 1;
  int cum = 0;
  for (int w = 0; w != 10001; ++w) {
    if (w2i[w]) {
      w2i[w] = cum++;
      i2w.push_back(w);
    }
  }
  vector<int> as;
  for (auto w : ws) as.push_back(w2i[w]);
  int cum_cost = 0;
  for (int i = 0; i != n; ++i) {
    int start = i;
    int pos = as[i];
    int cost = 0;
    int swap_counts = 0;
    while (pos != start) {
      ++swap_counts;
      cost += i2w[pos];
      pos = as[pos];
    }
    int cost_original = i2w[start] * swap_counts;
    int cost_with_swap = i2w[0] * swap_counts + (i2w[start] + i2w[0]) * 2;
    cum_cost += min(cost_original, cost_with_swap);
  }
  return cum_cost;
}
