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;
bool cmp(const int n1, const int n2) { return n1 < n2; }
struct Data {
  int num;
  int i;
};
int main() {
  int n;
  int minValue = INT_MAX;
  int sortAry[1000];
  Data ary[1000];
  vector<vector<int>> groups;
  int cost = 0;
  cin >> n;
  for (int i = 0; i < n; i++) {
    int temp;
    cin >> temp;
    sortAry[i] = ary[i].num = temp;
    minValue = min(minValue, temp);
  }
  sort(sortAry, sortAry + n, cmp);
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      if (ary[i].num == sortAry[j]) {
        ary[i].i = j;
        break;
      }
    }
  }
  for (int i = 0; i < n; i++) {
    vector<int> group;
    int j = i;
    int s = i;
    while (j != ary[j].i) {
      group.push_back(ary[j].num);
      int temp = ary[j].i;
      ary[j].i = j;
      j = temp;
    }
    if (!group.empty()) {
      groups.push_back(group);
    }
  }
  for (int i = 0; i < groups.size(); i++) {
    int sum = 0;
    int m = INT_MAX;
    int num = groups[i].size();
    for (int j = 0; j < num; j++) {
      sum += groups[i][j];
      m = min(groups[i][j], m);
    }
    int c1, c2;
    c1 = sum + (num - 2) * m;
    c2 = sum + (num + 1) * minValue + m;
    cost += min(c1, c2);
  }
  cout << cost << endl;
  return 0;
}
