/* The problem is a lot harder than I initially thought. I have now been spoiled with the solution, so there is no point in me making it, it would be the same as other peoples sol's. However, I can still try to make cheesy solutions. */ #pragma GCC optimize("Ofast,unroll-loops") #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 oo = 1e9, H = 1e6; int dist(int pos, int to){ if (pos < H){ if (pos <= to) return to - pos; else return (H-pos) + (H-to); }else{ int now = H*2-pos; if (now >= to) return now-to; else return now + to; } } int revdist(int pos, int to){ return dist ((H*2-pos)%(H*2), to); } mt19937 rng; int rnd(int l, int r){ return uniform_int_distribution(l,r)(rng); } int main(){ cin.tie(NULL),ios::sync_with_stdio(false); rng.seed(chrono::high_resolution_clock::now().time_since_epoch().count()); int n; cin >> n; vi f(n), t(n); for(auto& c : f) cin >> c; for(auto& c : t) cin >> c; auto F = [&](array times, ll ext) -> ll { int time = 0; ll score = 0; int lastpos = 0; rep(i,0,n){ ll minscore = 1e18; int mintime = 1e9; for(auto off : times){ int cur = (time + off) % (H*2); // take with extra cost { int prevt = revdist(cur, lastpos); int newpos = (cur + H*2 - prevt) % (H*2); int distto = dist(newpos, f[i]); ll curscore = distto + ext * min((int)(1+1e9/prevt/ext), prevt)*prevt; if (curscore < minscore ) { // can travel back in time!! and distto - prevt >= 0 mintime = distto - prevt; minscore = curscore; } } // take for free { int tolast = dist(cur, lastpos); int newt = (cur+tolast)%(H*2); int tonxt = dist(newt, f[i]); int curtime = tolast + tonxt; if (curtime < minscore){ mintime = curtime; minscore = curtime; } } } time += mintime + t[i]; score += minscore; lastpos = f[i]; } return score + accumulate(all(t),0ll); }; ll ans = 1e18; auto t1 = chrono::high_resolution_clock::now(); int iters = 0; while(chrono::duration_cast(chrono::high_resolution_clock::now()-t1).count() < 1700){ // { ++iters; array times; times[0] = 0; rep(i,1,4) times[i] = rnd(1,H*2-1); for(ll ext = 1; ext < 5e6; ext = (ext*6+4)/5){ ll score = F(times, ext); for(ll jmp = 1<<19; jmp; jmp/=2){ rep(iter,0,50){ auto nxt = times; rep(i,1,4) nxt[i] = (H*2 + nxt[i] + rnd(-jmp,jmp)) % (H*2); auto ret = F(nxt, ext); if (ret < score){ score = ret; times = nxt; } } } } ans = min(ans, F(times, 1e9)); } cerr << iters << '\n'; cout << ans << '\n'; }