#include <bits/stdc++.h>
#define ii pair<int, int>
#define fi first
#define se second
#define siz(v) ((int)(v).size())
#define all(v) begin((v)), end(v)
#define BIT(x, i) (((x) >> (i)) & 1)
#define MASK(i) (1LL << (i))
#define TIME (1.0 * clock() / CLOCKS_PER_SEC)
#define dbg(x) "[" #x " = " << x << "]"
#define lli pair<long long, int>
#define left __left
#define right __right
using namespace std;
bool M1;
const int MAXN = 5005, MAXK = 16, LOG = 20, infINT = 1e9 + 23737;
const long long inf = 1e18 + 5;
const int dx[4] = {-1, 0, 0, 1};
const int dy[4] = {0, -1, 1, 0};
template<class X, class Y> bool minimize(X &x, const Y &y){return x > y ? x = y, 1: 0;}
template<class X, class Y> bool maximize(X &x, const Y &y){return x < y ? x = y, 1: 0;}
int numVal, val[MAXN], pos[MAXN], cnt[MAXN][MAXN], bigger[MAXN][MAXN], pre[MAXN], f[MAXN];
void input(){
cin >> numVal;
for(int i = 1; i <= numVal; i++){
cin >> val[i], pos[val[i]] = i;
}
}
int get(const int &L, const int &R){
return cnt[R][R] - cnt[L - 1][R] - cnt[R][L - 1] + cnt[L - 1][L - 1];
}
void solve(){
for(int i = 1; i <= numVal; i++){
pre[i] = pre[i - 1] + pos[i];
}
for(int i = 1; i <= numVal; i++){
for(int j = i + 1; j <= numVal; j++){
if (pos[i] < pos[j]) cnt[i][j]++;
}
}
for(int i = 1; i <= numVal; i++){
for(int j = 1; j <= numVal; j++){
cnt[i][j] += cnt[i - 1][j] + cnt[i][j - 1] - cnt[i - 1][j - 1];
}
for(int j = 1; j <= numVal; j++){
bigger[i][j] = bigger[i][j - 1] + (val[j] > i);
}
}
memset(f, 0x3f, sizeof f);
f[0] = 0;
for(int i = 1; i <= numVal; i++){
int sum = 0;
for(int j = i; j >= 1; j--){
sum += bigger[i][pos[j] - 1];
minimize(f[i], f[j - 1] + get(j, i) + sum);
}
}
cout << f[numVal] << '\n';
cerr << f[numVal] << '\n';
}
bool M2;
signed main(){
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define task "test"
if (fopen(task".inp", "r")){
freopen(task".inp", "r", stdin);
freopen(task".out", "w", stdout);
}
int t = 1;
// cin >> t;
while(t--){
input();
solve();
}
cerr << TIME << ".s\n";
cerr << (&M2 - &M1) / 1048576 << " MB\n";
}