#include <bits/stdc++.h>
#define MAXN 200010
#define pii pair<int,int>
#define fi first
#define se second
#define pb push_back
#define all(x) begin(x),end(x)
#define lld long long
#define PRINT(x) cerr<<#x<<'='<<x<<endl;
using namespace std;
lld rez;

int levo[MAXN], sadrzi[MAXN], idx[2*MAXN], bit[2*MAXN];
void update(int idx, int val) {
    while(idx < 2*MAXN) {
        bit[idx] += val;
        idx += idx&-idx;
    }
}
int query(int idx) {
    int rez = 0;
    while(idx) {
        rez += bit[idx];
        idx -= idx&-idx;
    }
    return rez;
}
long long Resi(int N, int *A, int *B) {
    for(int i = 0; i < N; i++) {
        idx[A[i]] = (i+1);
        idx[B[i]] = -(i+1);
    }
    for(int i = 0; i < 2*N; i++) {
        if(idx[i] > 0) {
            levo[idx[i]-1] = query(i+1);
            update(i+1, +1);
        } else {
            sadrzi[-idx[i]-1] = query(i+1) - levo[-idx[i]-1];
            update(i+1, -1);
        }
    }
    for(int i = 0; i < N; i++) {
        rez += min(levo[i], sadrzi[i]);
    }
    return rez;
}