#include using namespace std; using i64 = int_fast64_t; using ui64 = uint_fast64_t; #define REP(i, n) for (i64 (i) = 0; (i) < (n); ++(i)) #define FOR(i, a, b) for (i64 (i) = (a); (i) < (b); ++(i)) i64 res = 1LL << 60; int N; vector B; signed main() { cin >> N; B.resize(N); REP(i, N) cin >> B[i]; { set> st; REP(i, N) { if (B[i]) st.emplace(i, B[i]); } i64 tmp = 0; REP(i, N) { auto itr = st.lower_bound(make_pair(i, 0)); if (itr == st.end()) itr = prev(itr); pair p = *itr; p.second--; st.erase(itr); tmp += abs(p.first - i); if (p.second > 0) st.emplace(p); } res = min(res, tmp); } { set> st; REP(i, N) { if (B[N - 1 - i]) st.emplace(i, B[N - 1 - i]); } i64 tmp = 0; REP(i, N) { auto itr = st.lower_bound(make_pair(i, 0)); if (itr == st.end()) itr = prev(itr); pair p = *itr; p.second--; st.erase(itr); tmp += abs(p.first - i); if (p.second > 0) st.emplace(p); } res = min(res, tmp); } cout << res << endl; }