#include <bits/stdc++.h>
#define L(i, j, k) for(int i = (j); i <= (k); i++)
#define R(i, j, k) for(int i = (j); i >= (k); i--)
#define sz(a) ((int) a.size())
#define pb emplace_back
#define me(a, x) memset(a, x, sizeof(a))
#define fst first
#define snd second
using namespace std;
typedef long long ll;
const int N=2e5+5;
const ll INF=1e18;
int p[N];
ll f[N],a[N];
void chmin(ll &a,ll b){
a=min(a,b);
}
long long min_total_length(std::vector<int> r, std::vector<int> b) {
int n=sz(r),m=sz(b);
vector<pair<int,int>>at;
L(i,0,n-1){
at.pb(r[i],1);
}
L(i,0,m-1){
at.pb(b[i],0);
}
sort(at.begin(),at.end());
int c=0;
L(i,0,sz(at)-1){
if(i==0||at[i].snd!=at[i-1].snd){
p[c++]=i;
}
}
int tot=sz(at);
p[c]=tot;
L(i,0,tot-1)a[i]=at[i].fst;
L(i,1,tot)f[i]=INF;
L(i,1,c-1){
ll sf=0;
R(l,p[i]-1,p[i-1]){
chmin(f[l],f[l+1]);
//~ cout<<sf<<endl;
sf+=a[l];
ll pf=0;
L(r,p[i]+1,p[i+1]){
pf+=a[r-1];
ll tl=sf+max((r-p[i])-(p[i]-l),0)*a[p[i]-1];
ll tr=pf+max((p[i]-l)-(r-p[i]),0)*a[p[i]];
chmin(f[r],f[l]+tr-tl);
}
}
}
return f[tot];
}