//#include<cstdio>
#include<iostream>
#include<algorithm>
#define MAX 1000
#define VMAX 10000
using namespace std;
int n, s, A[MAX], B[MAX], T[VMAX+1];

int solve()
{
  int ans = 0;
  int m, an, S;
  bool V[MAX];
  sort(B, B+n);
  for(int i=0; i<n; i++)
  {
    T[B[i]] = i;
    V[i] = false;
  }
  for(int i=0; i<n; i++)
  {
    if(V[i]) continue;
    m = VMAX;
    an = 0;
    S = 0;
    int cur = i;
    while(1)
    {
      V[cur] = true;
      an++;
      int v = A[cur];
      m = min(v, m);
      S += v;
      cur = T[v];
      if(V[cur]) break;
    }
    ans += min(S + (an - 2)*m, S + m + (an+1)*s);
  }
  return ans;
}
int main()
{
  cin >> n;
  s = VMAX;
  for(int i=0; i<n; i++)
  {
    cin >> A[i];
    B[i] = A[i];
    s = min(s, A[i]);
  }
  int ans = solve();
  cout << ans << endl;

  return 0;
}

