#include <stdio.h>
#define MAX 1000
#define VMAX 10000

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

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

int main(){
  int i,ans;
  scanf("%d",&n);
  s = VMAX;
  for(i=0;i<n;i++){
    scanf("%d",A[i]);
    s = min(s,A[i]);
  }
  ans = solve();
  printf("%d\n",ans);
  return 0;
}