#define ll long long
#include <algorithm>
#include <queue>
using namespace std;

int n;
int *a, *b;
priority_queue<pair<int,int> > v;
pair<int,int> *pov;
int kor, sz = 0;
priority_queue<int> izb;
ll res = 0;
bool mesto(int j, int i)
{
    if(i > j && (pov[i].first > i || pov[i].first == 0)) return 1;
    if(i < j) return 1;
    return 0;
}
long long Resi(int N, int *A, int *B)
{

    n = N;
    a = A;
    b = B;
    pov = new pair<int,int>[n+20];
    for(int i = 0; i < n; i++)
    {
        v.push(pair<int,int>(b[i], a[i]));
    }

    for(int i = 2 * n - 1; i >= 0; i--)
    {
        if(!izb.empty() && izb.top() == i)
        {
            //cout << i << " izb\n";
            if(i == kor) kor = pov[i].first;
            pov[pov[i].second].first = pov[i].first;
            izb.pop();
            sz--;
        }
        else
        {
            int p = v.top().second;
            if(sz == 0)
            {
                kor = p;
                //cout << p << " pov\n";
            }
            else
            {
                int j;
                for(j = kor; !mesto(p, j); j = pov[j].first, res++);
                //cout << j << " nas\n";
                if(j == kor) kor = p;
                pov[pov[j].second].first = p;
                pov[p].second = pov[j].second;
                pov[p].first = j;
                pov[j].second = p;
                //stampajpov(kor);
            }
            izb.push(v.top().second);
            v.pop();
            sz++;
        }
    }

    return res;
}