#include<bits/stdc++.h>
#define LL long long
using namespace std;
const int N = 2e5 + 5;
int n;
LL ans, u, v;
// 权值线段树
struct Node{
int ls, rs;
int size;
}tr[22 * N];//N * logN的空间
int cnt;
void insert(int &now, int l, int r, int val){
tr[now = ++ cnt].size ++ ;
if(l == r) return;
int mid = l + r >> 1;
if(val <= mid) insert(tr[now].ls, l, mid, val);
else insert(tr[now].rs, mid + 1, r, val);
// 不用 pushup
}
// 类似归并排序 求逆序对
int merge(int p, int q, int l, int r){
if(!q || !p) return p + q;
if(l == r){
tr[p].size += tr[q].size;
return p; // 删除 q
}
u += (LL)tr[tr[p].rs].size*tr[tr[q].ls].size; //交换前
v += (LL)tr[tr[p].ls].size*tr[tr[q].rs].size; //交换后
int mid = l + r >> 1;
tr[p].ls = merge(tr[p].ls, tr[q].ls, l, mid);
tr[p].rs = merge(tr[p].rs, tr[q].rs, mid + 1, r);
tr[p].size = tr[tr[p].ls].size + tr[tr[p].rs].size;
return p;
}
int dfs(){
int root, val;
scanf("%d", &val);
if(!val){
int ls = dfs(), rs = dfs();
u = 0; v = 0; //清零 // u 代表不换 v 代表换
root = merge(ls, rs, 1, n);
ans += min(u, v);
}
else insert(root, 1, n, val);
return root;
}
int main(){
scanf("%d", &n);
dfs(); // 递归读入
printf("%lld", ans);
return 0;
}