#include "wiring.h"
#include <bits/stdc++.h>
using namespace std;
#define ll long long
long long min_total_length(vector<int> R, vector<int> B) {
int N = R.size(), M = B.size();
vector <pair<int, int>> points(1);
for (int i = 0; i < N; i++) {
points.push_back({R[i], 0});
}
for (int i = 0; i < M; i++) {
points.push_back({B[i], 1});
}
sort(points.begin(), points.end());
int K = N+M;
vector <int> dp(K+5, 1e9);
dp[0] = 0;
auto Matching = [&](int l, int r) {
int ptr = 0, len = 0;
int ret = 0;
for (int j = l; j <= r; j++) {
ret += (points[j].second == points[l].second ? -1 : 1)*points[j].first;
}
for (int j = l; j < r; j++) {
len++;
if (points[j].second != points[j+1].second) {
ptr = j;
break;
}
}
int lf = len, rg = (r-l+1)-len;
if (lf < rg) ret -= points[ptr].first*(rg-lf);
else ret += points[ptr+1].first*(lf-rg);
return ret;
};
return Matching(1, K);
for (int i = 1; i <= K; i++) {
bool z = 0;
ll ptr = 0;
for (int j = i-1; j >= 1; --j) {
if (points[i].second == points[j].second) {
if (z) break;
}
else {
z = 1;
dp[i] = min(dp[i], dp[j-1]+Matching(j, i));
}
}
}
return dp[K];
}