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>
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define repr(i, n) for (int i = (n); i >= 0; --i)
#define FOR(i, m, n) for (int i = (m); i < (n); ++i)
#define FORR(i, m, n) for (int i = (m); i >= (n); --i)
using namespace std;
typedef long long ll;
const ll mod = 1000000007;
const ll mod2 = 998244353;

int minw = 10005;
bool seen[1005];


ll calcost(vector<pair<int, int> >& w, int id) {
  if (seen[id] || id == w[id].second) {
    seen[id] = true;
    return 0;
  }
  int k = id;
  int wsum = 0;
  int n = 0;
  int minpw = 100005;
  while(!seen[k]) {
    seen[k] = true;
    int value = w[k].first;
    minpw = min(minpw, value);
    wsum += value;
    k = w[k].second;
    n++;
  }
  ll cost1 = wsum + (n-2) * minpw;
  ll cost2 = wsum + minpw + (n+1) * minw;
  ll cost = min(cost1, cost2);
  return cost;
}

int main() {
  int n;
  cin >> n;
  vector<pair<int, int> > w(n);
  rep(i, n) {
    cin >> w[i].first;
    minw = min(minw, w[i].first);
    w[i].second = i;
  }
  sort(w.begin(), w.end());
  ll ans = 0;
  rep(i, n) {
    ans += calcost(w, i);
  }
  cout << ans << endl;
  
  return 0;
}
