#include <bits/stdc++.h>
#define maxn 200010
using namespace std;

int fwt[maxn], n;
long long ansB;
vector<pair<int, int> > b, a;
list<int> ls;
vector<pair<pair<int, int>, int> > ev;

int sum(int x){
    int res = 0;
    for(; x; x -= (x&-x)){
        res += fwt[x];
    }
    return res;
}

void ubaci(int x){
    for(; x < maxn; x += (x&-x)){
        ++fwt[x];
    }
}

void rek(int idx, long long tmpRes){
    if(2*n == idx){
        ansB = min(ansB, tmpRes);
        return;
    }
    int tmp = ev[idx].second;
    if(ev[idx].first.second == 0){
        for(auto i = ls.begin(); i != ls.end(); ++i){
            if(*i == tmp){
                ls.erase(i);
                break;
            }
            ++tmpRes;
        }
        rek(idx+1, tmpRes);
    } else {
        ls.push_back(tmp);
        rek(idx+1, tmpRes);
        ls.pop_back();
        ls.push_front(tmp);
        rek(idx+1, tmpRes);
        ls.pop_front();
    }
}

long long Resi(int N, int *A, int *B){
    if(N <= 20){
        n = N;
        for(int i = 0; i < N; ++i){
            ev.push_back({{B[i], 0},i+1} );
            ev.push_back({{A[i], 1}, i+1} );
        }
        sort(ev.begin(), ev.end());
        ansB = 1e17;
        rek(0, 0);
        return ansB;
    }
    for(int i = 0; i < N; ++i){
        a.push_back({A[i], i+1});
    }
    sort(a.begin(), a.end());
    int ans = 0;
    for(int i = 0; i < N; ++i){
        int tmp = a[i].second;
        tmp--;
        ans += min(sum(B[tmp]+1), i-sum(B[tmp]+1));
        ubaci(B[tmp]+1);
    }
    return ans;
};