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 main() {
  int n;
  int w[1000];
  int sorted_w[1000];
  bool has_arrived[1000] = {false};
  int pos_save[10010];
  long long sumcost = 0;
  int min_cycle;
  int min_all;
  int origin_pos;
  int move_pos;
  int num_cycle;
  int sum_cycle;
  int plan_inside, plan_outside;
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> w[i];
    sorted_w[i] = w[i];
    pos_save[w[i]] = i;
  }
  sort(sorted_w, sorted_w + n);
  min_all = sorted_w[0];
  for (int i = 0; i < n; i++) {
    min_cycle = w[i];
    sum_cycle = w[i];
    origin_pos = i;
    move_pos = pos_save[sorted_w[i]];
    num_cycle = 0;
    while (move_pos != origin_pos && !has_arrived[i]) {
      num_cycle++;
      min_cycle = min(min_cycle, w[move_pos]);
      sum_cycle += w[move_pos];
      has_arrived[origin_pos] = true;
      has_arrived[move_pos] = true;
      move_pos = pos_save[sorted_w[move_pos]];
    }
    if (num_cycle) {
      plan_inside = num_cycle * min_cycle + sum_cycle - min_cycle;
      plan_outside = 2 * min_all + 2 * min_cycle + min_all * num_cycle +
                     sum_cycle - min_cycle;
      sumcost += min(plan_inside, plan_outside);
    }
  }
  cout << sumcost << endl;
  return 0;
}
