// NOTE: this implementation may contain errors ^^' // // solution in n*log(n)^2 // idee: // we determine the minimum cost for each floor (n times) // for the ith floor we start with level in[i]+1. // Therefore we can kill all enemies in the range [i, i+1) // now we determine two person outside of the current range which are: (takes log(n)) // - as close as possible // - have a level whose MSB is >= the MSB of our level // if we can't kill any of those two we increase our starting level to be able to do so // We can kill the one with lower level // => our MSB increases (this can only happen log(n) times) #include using namespace std; #define all(x) begin(x), end(x) #define sz(x) (ll)(x).size() using ll = long long; using ld = long double; constexpr ll bits = 46; constexpr ll limN = 500007; constexpr ll inf = 0x3FFFFFFFFFFFFFF; vector arr[bits]; ll in[limN], pref[limN]; void add(ll x, ll i) { in[i] = x; pref[i + 1] = pref[i] + in[i]; for (ll j = 0; j < bits; j++) { if ((1ll << j) <= in[i]) arr[j].push_back(i); } } // is __lg(0) defined? ll mylog(ll x) { if (x == 0) return 0; else return __lg(x); } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); ll n; cin >> n; add(inf, 0); { deque tmp(n); for (ll i = 0; i < n; i++) cin >> tmp[i]; ll ma = *max_element(all(tmp)); while (tmp[0] != ma) { tmp.push_back(tmp[0]); tmp.pop_front(); } for (ll i = 0; i < n; i++) add(tmp[i], i+1); } add(inf, n+1); ll res = inf; for (ll i = 1; i <= n; i++) { ll cur = in[i]; ll l = i; ll r = i + 1; while (l > 1 || r < n + 1) { ll tmp = cur + pref[r] - pref[l]; ll tmpBits = min(bits-1, mylog(tmp)); r = *lower_bound(all(arr[tmpBits]), r); l = *prev(upper_bound(all(arr[tmpBits]), l)) + 1; tmp = cur + pref[r] - pref[l]; if (l > 1 || r < n + 1) { cur += max(0ll, min(in[l - 1], in[r]) - tmp); in[l-1] < in[r] ? l--: r++; } } res = min(res, cur); } cout << res << endl; }