#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
vector <int> order;
#define MAXN 200005
int a[MAXN];
int b[MAXN];
int n;
bool cmp(pii x,pii y)
{
    ll v1 = (x.second==1)?a[x.first]:b[x.first];
    ll v2 = (y.second==1)?a[y.first]:b[y.first];
    return v1<v2;
}
ll bit[MAXN];
void update(int idx,int val)
{
    while(idx < MAXN)
    {
        bit[idx]+=val;
        idx+=idx&(-idx);
    }
}
ll get(int idx)
{
    ll ret = 0LL;
    while(idx > 0)
    {
        ret+=bit[idx];
        idx-=idx&(-idx);
    }
    return ret;
}

vector <pii> evs;

long long Resi(int N, int *A, int *B)
{
    for(int i = 0; i < N;i++)A[i]++,B[i]++;
    for(int i = 0; i < N;i++)a[i]=A[i],b[i]=B[i];
    n = N;
    for(int i = 0; i < N; i++)
    {
        evs.push_back({i,1});
        evs.push_back({i,-1});
        //order.push_back(i);
    }
    sort(evs.begin(),evs.end(),cmp);
    ll ans = 0LL;
    for(int j = 0; j < n*2; j++)
    {
        int i = evs[j].first;
        update(b[i],evs[j].second);
        if(evs[j].second==-1)continue;
        ans += min(get(b[i]-1),get(MAXN-1)-get(b[i]));
    }
    return ans;
}