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 std::printf;
using std::scanf;
const int kMaxN = 1000;
const int kMaxWi = 10000;
int MakeCycle(int w[], int i, int remain[], int cycle[]) {
  int j = 0;
  cycle[0] = -1;
  while (w[i] != cycle[0]) {
    cycle[j] = w[i];
    ++j;
    remain[i] = 0;
    i = w[i] - 1;
  }
  return j;
}
int CompareCosts(int cycle[], int cycle_n, int cycle_min, int w_min) {
  if (cycle_n == 1) {
    return 0;
  } else if (cycle_n == 2) {
    return cycle[0] + cycle[1];
  } else {
    int cycle_sum, i, cost1, cost2;
    cycle_sum = 0;
    for (i = 0; i < cycle_n; ++i) {
      cycle_sum += cycle[i];
    }
    cost1 = cycle_sum + (cycle_n - 2) * cycle_min;
    cost2 = cycle_sum + cycle_min + (cycle_n + 1) * w_min;
    return std::min(cost1, cost2);
  }
}
int main() {
  int n, i, j, cycle_n, cycle_min, w_min, cnt;
  scanf("%d", &n);
  int w[n], remain[n], cycle[n];
  for (i = 0; i < n; ++i) {
    scanf("%d", &w[i]);
  }
  w_min = kMaxWi;
  for (i = 0; i < n; ++i) {
    w_min = std::min(w_min, w[i]);
  }
  for (i = 0; i < n; ++i) {
    remain[i] = 1;
  }
  cnt = 0;
  for (i = 0; i < n; ++i) {
    if (remain[i]) {
      cycle_n = MakeCycle(w, i, remain, cycle);
      cycle_min = kMaxWi;
      for (j = 0; j < cycle_n; ++j) {
        cycle_min = std::min(cycle_min, cycle[j]);
      }
      cnt += CompareCosts(cycle, cycle_n, cycle_min, w_min);
    }
  }
  printf("%d\n", cnt);
  return 0;
}
