#include "wiring.h"
#include <bits/stdc++.h>
using namespace std;
#define int int64_t
const int M = 1e16;
long long min_total_length(std::vector<int32_t> r, std::vector<int32_t> b) {
vector<vector<int>> a;
a.push_back({-M});
vector<int> o;
int j1 = 0 , j2 = 0;
while(j1 < r.size() || j2 < b.size()){
if(j1 >= r.size() || (j2 < b.size() && b[j2] < r[j1])){
swap(j1 , j2);
swap(r , b);
if(!o.empty())a.push_back(o);
o.clear();
}
o.push_back(r[j1]);
j1++;
}
a.push_back(o);
a.push_back({M});
vector<int> dp1 = {0} , dp2 = {0};
for(int i = 1; i < a.size()-1; i++){
int s = a[i].size();
vector<int> dp(s+1 , M);
int e = M , f = 0;
for(int j = 1; j <= s; j++){
if(dp1.size() > j)e = min(e , dp1[j]);
f += a[i][j-1]-a[i-1].back();
//cout <<"1:"<< a[i][j]-a[i-1].back() << endl;
dp[j] = e+f;
}
e = M , f = 0;
for(int j = dp2.size()-1; j > s; j--)e = min(e , dp2[j]);
for(int j = 1; j <= s; j++){
f += a[i][s-j]-a[i][0];
}
for(int j = s; j >= 1; j--){
if(dp2.size() > j)e = min(e , dp2[j]);
//cout <<"2:" << a[i][s-j]-a[i][0] << endl;
dp[j] = min(e+f , dp[j]);
f -= a[i][j-1]-a[i][0];
}
dp[0] = min(dp1[0] , dp2[0]);
dp1.assign(s+1 , 0);
dp2.assign(s+1 , 0);
int w1 = 0, w2 = 0;
for(int j = 0; j <= s; j++){
dp1[j] = dp[s-j]+w1;
dp2[j] = dp[s-j]+w2;
if(j != s)w1 += a[i][s-1]-a[i][s-j-1];
if(j != s)w2 += a[i+1][0]-a[i][s-j-1];
}
}
return dp1[0];
}