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 = 100000;

int n;
vector<int> w;
vector<bool> seen;
vector<int> a;
vector<int> t;
int min_w = MAX;

int calc_cycle(int s) {
  seen[s] = true;
  int cycle_min_w = w[s];
  int cycle_len = 1;
  int next =  t[w[s]];
  int cycle_sum = w[s];
  if (next == s) return 0;
  while (!seen[next]) {
    seen[next] = true;
    cycle_min_w = min(cycle_min_w, w[next]);
    cycle_len ++;
    cycle_sum += w[next];
    next = t[w[next]];
  }
  return min(cycle_sum + (cycle_len - 2) * cycle_min_w, cycle_sum + cycle_min_w + (cycle_len + 1) * min_w);
}

int main() {
  cin >> n;
  w.resize(n);
  seen.resize(n, false);
  t.resize(MAX);
  for (int i = 0; i < n; i++) {
    cin >> w[i];
    min_w = min(min_w, w[i]);
  }

  a = w;
  sort(a.begin(), a.end());
  for (int i = 0; i < n; i++) {
    t[a[i]] = i;
  }

  int ans = 0;
  for (int i = 0; i < n; i++) {
    if (seen[i]) continue;
    ans += calc_cycle(i);
  }
  cout << ans << endl;
}
