#include "wiring.h"
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef pair<int,int> pi;
typedef pair<pi,ll> pil;
auto cmp = [](pil a, pil b){return a.second > b.second;};
typedef priority_queue<pil,vector<pil>,decltype(cmp)> pqpil;
ll min_total_length(vi r, vi b) {
pqpil pq(cmp);
pq.push({{0,0},abs(r[0] - b[0])});
set<pi> S;
for(;1;){
pil t = pq.top();
int ri = t.first.first, bi = t.first.second;
ll d = t.second;
pq.pop();
if(S.count({ri,bi})) continue;
S.insert({ri,bi});
if(ri == r.size()-1 && bi == b.size()-1) return d;
if(ri < r.size()-1) pq.push({{ri+1,bi},d + abs(r[ri+1]-b[bi])});
if(bi < b.size()-1) pq.push({{ri,bi+1},d + abs(r[ri]-b[bi+1])});
if(ri < r.size()-1 && bi < b.size()-1) pq.push({{ri+1,bi+1},d + abs(r[ri+1]-b[bi+1])});
}
return -1;
}