#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
pair<int,int> p[500000];
int bit[500000];
int n;

/*
3
1 5
2 7
3 6
*/

void update(ll x)
{
    while(x<=n*3){
        bit[x]++;
        x+=x&(-x);
        //cout << x<<endl;
    }
}

ll get(ll x)
{
    ll temp=0;
    while(x>0){
        temp+=bit[x];
        x-=x&(-x);
        //cout << "get"<<endl;
    }
    return temp;
}


long long Resi(int N, int *A, int *B)
{
    ll vrati=0;
    if(N==1){
        return 0;
    }
    else if(N==2){
        return 0;
    }

    for(int i=0;i<N;i++){
        p[i]={A[i]+1,B[i]+1};
    }
    sort(p,p+N);
    n=N;

    if(N<=20){
        deque<int> dq,bio;
        vrati=INT_MAX;
        for(int mask=0;mask<(1LL<<N);mask++){
            dq.clear();
            int poredu=0;
            int temp=0;
            for(int i=0;i<N*2;i++){
                if(p[i].second==p[i].first){
                    ll obrisan=0;
                    for(int j=0;j<dq.size();j++){
                        if(bio[j])obrisan++;
                        else if(dq[j]==p[i].second){
                            temp+=j-obrisan;
                            bio[j]=1;
                            break;
                        }
                    }
                }
                else{
                    if(mask & (1LL<<poredu)){
                        dq.push_back(p[i].second);
                        bio.pb(0);
                    }
                    else{
                        dq.push_front(p[i].second);
                        bio.push_front(0);
                    }
                    poredu++;
                }
            }
            //cout << temp <<endl;
            vrati=min((int)vrati,temp);
        }
        return vrati;
    }

    deque<ll> dq;
    dq.push_back(p[0].second);
    update(p[0].second);
    //cout << "xxx";
    ll maxi=0,mini=INT_MAX;
    for(int i=1;i<N;i++){
        /*
        while(bio[dq.front()]==1){
            dq.pop_front();
        }
        while(bio[pq.back()]==1){
            dq.pop_back();
        }*/
            ll temp=get(p[i].second);
            if(dq.size()-temp<=temp){
                update(p[i].second);
                vrati+=dq.size()-temp;
                dq.pb(p[i].second);
            }
            else{
                dq.push_front(p[i].second);
                vrati+=temp;
                update(p[i].second);
            }
    }

    //for(auto i:dq)cout << i << ' ';
    return vrati;
}