#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

#define ll long long
#define pb push_back
#define all(x) x.begin(),x.end()
#define f first
#define s second

using namespace __gnu_pbds;
using namespace std;
template<class T> using ordered_set=tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>;
template<class T1,class T2> ostream& operator<<(ostream& out,pair<T1,T2> a){out << "[" << a.f << "," << a.s << "]"; return out;}
template<class T> ostream& operator<<(ostream& out, vector<T> a){out << "{";for(auto p:a)out << p << ",";out << "}";return out;}

long long Resi(int N, int *A, int *B) {
	vector<pair<int,int> > events;
	ll sol=0;
	for(int i=0;i<N;i++)
    {
        events.pb({A[i],B[i]});
        events.pb({B[i],B[i]});
    }
    sort(all(events));
    ordered_set<int> s;
    cout << events << endl;
    for(auto p:events)
    {
        if(p.f==p.s)
            s.erase(p.f);
        else
        {
            //cout << p << endl;
            s.insert(p.s);
            int i=s.order_of_key(p.s);
            //printf("%i %i\n",i,s.size());
            sol+=min(i,(int)s.size()-i-1);
        }
    }
    return sol;
}