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

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

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;
    int glb=0;
    for(int i=0;i<v.size();i++)
    {
        if(active[v[i].second])
        {
            accnt--;
            for(int j=0;j<cur.size();j++)
            {
                if(cur[j]==v[i].second)
                {
                    for(int k=0;k<j;k++)
                    {
                        if(A[cur[k]]<B[v[i].second] && B[v[i].second]<B[cur[k]])
                        {
                            res++;
                        }
                    }
                    break;
                }
            }
            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(2*tmp<accnt)
            {
                cur.push_front(v[i].second);
            }
            else
            {
                cur.push_back(v[i].second);
            }
            accnt++;
        }
    }
    return res;
}