#include<iostream>
#include<algorithm>
using namespace std;
static const int MAX = 1000;
static const int VMAX = 10000;

int n, A[MAX], s;
int B[MAX], T[VMAX+1];

int solve(){

  int i, ans = 0;
  bool V[MAX];

  for (i=0; i<n; i++){
    B[i] = A[i];
    V[i] = false;
  }

  sort(B, B+n);

  for (i=0; i<n; i++) T[B[i]] = i;

  for (i=0; i<n; i++){
    if (V[i]) continue;
    int an = 0;
    int S = 0;
    int cur = i;
    int m = VMAX;
    while (1){
      V[cur] = true;
      an++;
      int v = A[cur];
      S += v;
      m = min(m, v);
      cur = T[v];
      if (V[cur]) break;
    }
    ans += min(S + (an - 2) * m, m + S + (an + 1) * s);
  }
  return ans;
}

int main(){
  s = VMAX;
  cin >> n;

  for (int i=0; i<n; i++){
    cin >> A[i];
    s = min(s, A[i]);
  }

  int ans = solve();
  cout << ans << endl;

  return 0;
}

