#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define mp make_pair
#define pb push_back
const int N=100050;
const int lim=2*N;
int n,a[N],b[N],id[N];
const int M=60*N;
//Segment Tree
int ls[M],rs[M],tsz,root,sum[M],root2;
void Set(int &c, int ss, int se, int qi, int f)
{
	if(!c) c=++tsz;
	sum[c]+=f;
	if(ss==se) return;
	int mid=ss+se>>1;
	if(qi<=mid) Set(ls[c],ss,mid,qi,f);
	else Set(rs[c],mid+1,se,qi,f);
}
int Get(int c, int ss, int se, int qs, int qe)
{
    if(qs>qe || qs>se || ss>qe) return 0;
    if(qs<=ss && qe>=se) return sum[c];
    int mid=ss+se>>1;
    return Get(ls[c],ss,mid,qs,qe)+Get(rs[c],mid+1,se,qs,qe);
}
//Splay Tree
int fa[N],go[N][2],sz[N];
void pull(int c){ sz[c]=sz[go[c][0]]+sz[go[c][1]]+1;}
int pd(int x){ return go[fa[x]][0]==x?0:go[fa[x]][1]==x?1:-1;}
void rot(int u)
{
	int x=fa[u],y=fa[x],tx=pd(u),ty=pd(x),v=go[u][tx^1];
	if(y) go[y][ty]=u;go[x][tx]=v;go[u][tx^1]=x;
	if(v) fa[v]=x;fa[u]=y;fa[x]=u;
	pull(x);pull(u);
}
void splay(int x){ for(;pd(x)!=-1;rot(x)) if(pd(fa[x])!=-1) rot(pd(x)==pd(fa[x])?fa[x]:x);}
int GetR(int x){ return go[x][1]?GetR(go[x][1]):x;}
int GetL(int x){ return go[x][0]?GetL(go[x][0]):x;}
void Merge(int x, int y)
{
	if(x==0 || y==0) return;
	int w=GetR(x);
	splay(w);
	go[w][1]=y;
	fa[y]=w;
	pull(w);
	rot(y);
}
void Print(int x){ if(!x) return;Print(go[x][0]);printf("%i ",x);Print(go[x][1]);}
ll Resi(int _N, int *A, int *B)
{
	srand(time(0));
	vector<int> tmp;
	n=_N;
	vector<pair<int,int>> evs;
	for(int i=1;i<=n;i++)
	{
		a[i]=A[i-1],b[i]=B[i-1];
		evs.pb({a[i],i});
		evs.pb({b[i],-i});
		sz[i]=1;
	}
	sort(evs.begin(),evs.end());
	ll ans=0;
	int last=0,mx=0,mn=0;
	for(int i=0;i<evs.size();i++)
	{
		int x=evs[i].second;
		if(x<0)
		{
			x=-x;
			Set(root,0,lim,b[x],-1);
			ans+=Get(root2,-lim,lim,-lim,id[x]-1);
			Set(root2,-lim,lim,id[x],-1);
			/*splay(x);
			ans+=sz[go[x][0]];
			int a=go[x][0];
			int b=go[x][1];
			//printf("x:%i a:%i b:%i %i\n",x,a,b,sz[a]);
			if(a) last=a;
			else last=b;
			fa[a]=0;fa[b]=0;
			Merge(a,b);*/
			/*int j;
			for(j=0;j<tmp.size();j++) if(tmp[j]==x) break;
			ans+=j;
			tmp.erase(tmp.begin()+j);*/
		}
		else
		{
			int cnt=Get(root,0,lim,b[x]+1,lim);
			int pre=Get(root,0,lim,0,b[x]);
			//printf("x:%i last:%i\n",x,last);
			if(pre>=cnt)
			{
				//Merge(last,x);
				id[x]=++mx;
			}
			else
			{
				id[x]=--mn;
                //Merge(x,last);
			}
			Set(root2,-lim,lim,id[x],1);
			Set(root,0,lim,b[x],1);
			//last=x;
			/*int j,cnt=0;
			for(j=0;j<tmp.size();j++) if(b[tmp[j]]>b[x]) cnt++;
			int pre=tmp.size()-cnt;
			if(pre>=cnt) tmp.pb(x);
			else tmp.insert(tmp.begin(),x);*/
		}
		//if(last) splay(last);
		//Print(last);
		//printf("\n");
	}
	return ans;
}
//-------------------------//
/*
int A[N],B[N];
int main()
{
	int n,i;
	scanf("%i",&n);
	for(int i=1;i<=n;i++) scanf("%i",&A[i]);
	for(int i=1;i<=n;i++) scanf("%i",&B[i]);
	printf("%lld\n",Resi(n,A+1,B+1));
	return 0;
}
*/
//-------------------------//