// @EXPECTED_RESULTS@: WRONG_ANSWER, TIME_LIMIT_EXCEEDED #include "bits/stdc++.h" using namespace std; #define rep(i,a,b) for(int i=(a); i<(b); ++i) #define all(x) x.begin(),x.end() #define sz(x) int(x.size()) typedef long long ll; typedef unsigned long long ull; typedef vector vi; typedef vector vvi; const int N = 1e6; // +1? int dist(int at, int to){ if (at >= N) { at = N*2-at; // always go up at = N-at; to = N-to; } if (to >= at) return to-at; return (N-at) + (N-to); } struct state{ array pos = {-1,-1,-1,-1}; ll t = 0; bool operator<(state& b){ return tie(t,pos) < tie(b.t,b.pos); }bool operator==(state& b){ return tie(t,pos) == tie(b.t,b.pos); } void move(int dt){ t += dt; rep(i,0,4) if (pos[i]>=0){ pos[i] = (pos[i] + dt) % (N*2); } } }; int main(){ cin.tie(NULL),ios::sync_with_stdio(false); int n; cin >> n; vi f(n), t(n); for(auto& c : f) cin >> c; for(auto& c : t) cin >> c; vector dp = {{}}; int at = 0; rep(iter,0,n){ decltype(dp) ndp; int to = f[iter]; for(auto cur : dp){ rep(i,0,4){ if (cur.pos[i] == -1){ rep(_,0,2){ auto nxt = cur; nxt.pos[i] = at; int dt = dist(at, to); nxt.move(dt + t[iter]); ndp.push_back(nxt); if (at != 0) at = N*2 - at; } }else{ rep(bounce,0,2){ // direct auto nxt = cur; int dt = dist(nxt.pos[i], at); nxt.move(dt); dt = dist(nxt.pos[i], to); nxt.move(dt); if (bounce) { nxt.move(1); dt = dist(nxt.pos[i], dt); nxt.move(dt); } nxt.move(t[iter]); ndp.push_back(nxt); } } } } for(auto& c : ndp) sort(all(c.pos)); sort(all(ndp)); ndp.erase(unique(all(ndp)),end(ndp)); dp = ndp; at = to; cerr << dp[0].t << '\n'; } cout << dp[0].t << '\n'; }