#include #pragma GCC target("avx2") #define rep(i, a, b) for (ll i = (a); i < (b); i++) #define all(x) (x).begin(), (x).end() #define sz(x) (ll)size(x) using namespace std; using ll = long long; using vi = vector; using vvi = vector; using pii = pair; #define TIME chrono::steady_clock::now().time_since_epoch().count() mt19937 rng(TIME); const double sec = 1.9; auto start = TIME; using S = array; using P = int; constexpr int L = 2e6; int n; vector f, t, dir; #define truemod(a) (((a) % L + L) % L) P eval(S x) { int time = 0, loc = 0; rep(i,0,n) { int best_wait = 1e9; for (int q : x) best_wait = min(best_wait, truemod((loc + q - time) * (dir[i] ?: -1))); time += best_wait + t[i]; loc = f[i]; } return time; } S mut(S x) { int ch = rng() % 3, gah = rng() % 2 * 2 - 1; x[ch] = truemod(x[ch] + (1 << (rng() % 20)) * gah); return x; } pair SA(S current, P price) { double p, t_start = 10, t_end = 1e-3; P obj = price; S best = current; auto accept = [&] (P new_price) { double t = t_start * pow(t_end / t_start, p); return bernoulli_distribution( min(1.0, exp((price - new_price) / t)) )(rng); }; while ((p = (TIME - start) / sec / 1e9) < 1) { S x = mut(current); P np = eval(x); if (accept(np)) current = x, price = np; if (price < obj) best = current, obj = price; } return {best, obj}; } void solve() { cin >> n; f.resize(n), t.resize(n); dir.resize(n); for (auto& x : f) cin >> x; ll ans = 0; for (auto& x : t) { cin >> x; ans += x / L * L; x %= L; } ll last = 0; rep(i,0,n) dir[i] = f[i] > last, t[i] += abs(last - f[i]), last = f[i]; S init{0, 0, 0, 0}; auto [best, obj] = SA(init, eval(init)); for (auto x : best) cerr << x << ' '; cout << ans + obj; } int main() { cin.tie(0)->sync_with_stdio(0); cin.exceptions(cin.failbit); solve(); return 0; }