#include #include using namespace std; #define rep(i, n) for (int i = 0; i < (int)(n); i++) #define all(x) (x).begin(), (x).end() #define ll long long #define ld long double #define INF 1000000000000000000 typedef pair pll; int main() { cin.tie(0); ios::sync_with_stdio(false); int N; cin >> N; stack st; ll ans = 0; rep(i, N) { ll a; cin >> a; if (a == 1) continue; if (st.empty()) { st.push({a, i}); } else if (a == 0) { int tar = st.top().first; if (tar == 0) { st.push({a, i}); } else { st.top().first--; ans += abs(st.top().second - i); if (st.top().first == 0) st.pop(); } } else { while (1) { if (st.empty()) { st.push({a, i}); break; } int tar = st.top().first; if (tar != 0) { st.push({a, i}); break; } else { a--; ans += abs(st.top().second - i); st.pop(); if (a == 0) break; } } } } cout << ans << endl; }