#include<stdio.h>
#include<stdlib.h>
#include<limits.h>



int n,cost;
int A[1001],B[1001];
int L[501],R[502];


void merge(int left,int mid,int right){
  int i,j,n1=mid-left,n2=right-mid;
  for(i=0;i<n1;i++) L[i]=A[left+i];
  L[n1]=INT_MAX;
  for(i=0;i<n2;i++) R[i]=A[mid+i];
  R[n2]=INT_MAX;
  int l=0,r=0;
  for(i=left;i<right;i++){
    if(L[l]<=R[r]){
      A[i]=L[l];
      l++;
    }
    else{
      A[i]=R[r];
      r++;
    }
  }
}


void m_sort(int left,int right){
  int mid;
  if( left+1 >= right) return;
  mid=(left+right)/2;
  m_sort(left,mid);
  m_sort(mid,right);
  merge(left,mid,right);
}


void swap(int a,int b){
  int swap;
  swap=B[a];
  B[a]=B[b];
  B[b]=swap;
  cost+=B[a]+B[b];
}


/*??£????????´??????????????°???????????§????°??????????????????¢?????????????????????*/
int min_search(){
  int res=n,i;
  for(i=0;i<n;i++){
    if(A[i]!=B[i]){
      if(B[res] >B[i]) res =i;
    }
  }
  return res;
}


int main(){
  scanf("%d",&n);
  int i,j,min=n;
  for(i=0;i<n;i++){
    scanf("%d",&A[i]);
    B[i]=A[i];
  }
  B[n]=INT_MAX;
  m_sort(0,n);
  cost=0;
  for(i=0;i<n;i++){
    for(j=i+1;j<n;j++){
      if(B[i]==A[j]){
        if(B[j]==A[i]) swap(i,j);
        break;
      }
    } 
  }
  while(1){
    if(min==n) min=min_search();
    if(min==n) break;
    for(i=0;i<n;i++){
      if(A[min]==B[i]){
        if(min==i){
          min=n;
          break;
        }
        swap(min,i);
        min=i;
        break;
      }
    }
  }
  printf("%d\n",cost);
  return 0;
}
   
          
          
    