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;
class UnionFind {
 private:
  int height[1000], parent[1000];
  int size;

 public:
  UnionFind(int size) : size(size) {
    for (int i = 0; i < size; ++i) {
      parent[i] = i;
    }
    fill(height, height + size, 0);
  }
  bool isUnited(int a, int b) { return root(a) == root(b); }
  int root(int n) {
    if (n == parent[n]) return n;
    return root(parent[n]);
  }
  void unite(int a, int b) {
    a = root(a), b = root(b);
    if (height[a] < height[b]) {
      parent[a] = b;
    } else if (height[a] > height[b]) {
      parent[b] = a;
    } else {
      parent[b] = a;
      height[b]++;
    }
  }
};
const int inf = 1e9;
int main() {
  int N;
  cin >> N;
  vector<int> v(N);
  for (int i = 0; i < N; ++i) {
    cin >> v[i];
  }
  map<int, int> m;
  for (int i = 0; i < N; ++i) {
    m[v[i]] = i;
  }
  vector<int> to = v;
  sort(to.begin(), to.end());
  UnionFind uf(N);
  for (int i = 0; i < N; ++i) {
    uf.unite(i, m[to[i]]);
  }
  map<int, int> g;
  vector<int> sum(N);
  vector<int> mn(N, inf);
  for (int i = 0; i < N; ++i) {
    int id = uf.root(i);
    sum[id] += v[i];
    mn[id] = min(mn[id], v[i]);
    g[id]++;
  }
  long long ans = 0;
  for (const pair<int, int>& p : g) {
    int i = p.first, n = p.second;
    ans += sum[i] - mn[i] +
           min(mn[i] * (n - 1), (to[0] + mn[i]) * 2 + to[0] * (n - 1));
  }
  cout << ans << endl;
}
