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

vector<pair<int,int>> v;
bool active[100005];
deque<int> cur;

long long Resi(int N, int *A, int *B)
{
    for(int i=0;i<N;i++)
    {
        v.push_back({A[i],i});
        v.push_back({B[i],i});
    }
    sort(v.begin(),v.end());
    long long res=0;
    for(int i=0;i<v.size();i++)
    {
        //printf("%d %d\n",v[i].first,v[i].second);
        if(active[v[i].second])
        {
            deque<int> cpy;
            for(int j=0;j<cur.size();j++)
            {
                if(cur[j]==v[i].second)
                {
                    res+=j;
                }
                else
                {
                    cpy.push_back(cur[j]);
                }
            }
            cur=cpy;
            active[v[i].second]=false;
        }
        else
        {
            active[v[i].second]=true;
            int tmp=0;
            for(int j=0;j<N;j++)
            {
                if(active[j] && B[j]<B[v[i].second])
                {
                    tmp++;
                }
            }
            if(tmp<cur.size())
            {
                cur.push_front(v[i].second);
            }
            else
            {
                cur.push_back(v[i].second);
            }
        }
    }
    return res;
}