#include<bits/stdc++.h>
using namespace std;
#define int long long

const int N = 1e5;
int a[N],b[N],check[N];
map<int,int> mp;

signed main(){

  int n; cin >> n;
  for(int i = 0; i < n; i++){
    cin >> a[i];
    b[i] = a[i];
    mp[a[i]] = i;
  }

  sort(b,b+n);
  int ans = 0;
  for(int i = 0; i < n; i++){
    int cost = 0,u = i,m = 1e9;
    int j = 0;
    for(; !check[u]; j++){
      m = min(m,a[u]);
      cost += a[u];
      check[u] = 1;
      u = mp[b[u]];
    }
    if(j >= 2){
      ans += min(cost+m+(j+1)*b[0],cost+(j-2)*m);
    }
  }
  cout << ans << endl;

  return 0;
}

