#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> P;
typedef vector<ll> vi;
typedef vector<vi> vvi;
typedef vector<P> vp;
typedef vector<bool> vb;
#define rep(i,n) for(ll i=0;i<(ll)(n);i++)
#define REP(i,k,n) for(ll i=(ll)(k);i<(ll)(n);i++)
#define all(a) a.begin(),a.end()
#define rsort(a) {sort(all(a));reverse(all(a));}
#define dupli(a) {sort(all(a));a.erase(unique(all(a)),a.end());}
#define lb(v,k) (lower_bound(all(v),k)-v.begin())
#define fi first
#define se second
#define pb emplace_back
template<class T> bool chmin(T&a,T b){if(a>b){a=b;return true;}return false;}
template<class T> bool chmax(T&a,T b){if(a<b){a=b;return true;}return false;}
template<class T> void out(T a){cout<<a<<'\n';}
template<class T> void outv(T v){rep(i,v.size()){if(i)cout<<' ';cout<<v[i];}cout<<'\n';}
template<class T> void outvv(T v){for(auto x:v)outv(x);}
template<class T> void outp(T p){cout<<'('<<p.fi<<','<<p.se<<')'<<endl;}
template<class T> void outvp(T v){for(auto p:v)cout<<'('<<p.fi<<','<<p.se<<')';cout<<endl;}
const ll inf=1001001001001001001;
ll minimum_walk(vector<int> p,int s){
int n=p.size();
vi gr(n,-1);
rep(i,n)if(p[i]==i)gr[i]=-2;
ll ans=0,c=0;
vp v;
rep(i,n)if(gr[i]==-1){
ll mi=i,ma=i;
gr[i]=c;
ll nw=p[i];
ans+=abs(nw-i);
while(nw!=i){
gr[nw]=c;
chmax(ma,nw);chmin(mi,nw);
ans+=abs(nw-p[nw]);
nw=p[nw];
}
c++;
v.pb(mi,ma);
}
v.pb(s,s);
if(gr[s]==-2)gr[s]=c;
if(n<=1000){
vvi dp(n,vi(n,inf));
ll a=0,b=n-1;
while(gr[a]==-2)a++;
while(gr[b]==-2)b--;
dp[a][b]=0;
function<ll(ll,ll)> dfs=[&](ll l,ll r){
if(dp[l][r]!=inf)return dp[l][r];
if(r!=n+1){
ll nl=l,nr=r+1;
if(gr[r+1]!=-2){
chmin(nl,v[gr[r+1]].fi);
chmax(nr,v[gr[r+1]].se);
}
chmin(dp[l][r],dfs(nl,nr)+2);
}
if(l){
ll nl=l-1,nr=r;
if(gr[l-1]!=-2){
chmin(nl,v[gr[l-1]].fi);
chmax(nr,v[gr[l-1]].se);
}
chmin(dp[l][r],dfs(nl,nr));
}
return dp[l][r];
};
ll sl=s,sr=s;
if(gr[s]!=-2){
chmin(sl,v[gr[s]].fi);
chmax(sr,v[gr[s]].se);
}
return dfs(s,s)+ans;
}
sort(all(v));
vp st;
for(auto x:v){
if(st.size()&&st.back().se>=x.fi)chmax(st.back().se,x.se);
else{
if(st.size())ans+=(x.fi-st.back().se)*2;
st.pb(x);
}
}
return ans;
}
int main(){
ll n;cin>>n;
vector<int> v(n);rep(i,n)cin>>v[i];
out(minimum_walk(v,0));
}
Compilation message
/tmp/ccrVprQn.o: In function `main':
grader.cpp:(.text.startup+0x0): multiple definition of `main'
/tmp/cc6QcM7q.o:books.cpp:(.text.startup+0x0): first defined here
collect2: error: ld returned 1 exit status