#include<bits/stdc++.h>usingnamespacestd;#define LL long long
constintMAXN=200005;intn;LLans=0,u=0,v=0;intcnt=0,roc=0,root[MAXN<<5],lc[MAXN<<5],rc[MAXN<<5],tree[MAXN<<5];intbuild(intl,intr,intp){intpos=++cnt;if(l==r){tree[pos]=1;returnpos;}intm=(l+r)>>1;if(p<=m)lc[pos]=build(l,m,p);elserc[pos]=build(m+1,r,p);tree[pos]=tree[lc[pos]]+tree[rc[pos]];returnpos;}intmerge(intr1,intr2,intl,intr){if(!r1||!r2)returnr1^r2;if(l==r){tree[r1]+=tree[r2];returnr1;}intm=(l+r)>>1;u+=(LL)tree[rc[r1]]*tree[lc[r2]];v+=(LL)tree[rc[r2]]*tree[lc[r1]];lc[r1]=merge(lc[r1],lc[r2],l,m);rc[r1]=merge(rc[r1],rc[r2],m+1,r);tree[r1]=tree[lc[r1]]+tree[rc[r1]];returnr1;}intdfs(){intx,pos;cin>>x;if(x==0){intls=dfs(),rs=dfs();u=v=0;pos=merge(ls,rs,1,n);ans+=min(u,v);}else{pos=build(1,n,x);}returnpos;}intmain(){cin>>n;dfs();cout<<ans<<endl;return0;}