Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- #define endl '\n'
- using ll = long long;
- const int N = 1e5 + 10;
- int n;
- ll a[N], pre[N], cost[N];
- int lst[N], lim[N], nxt[N];
- struct Node {
- ll lmi, rmi, mi, sum;
- };
- class Segment {
- private:
- ll a[N];
- Node node[N << 2];
- public:
- void init (int n, ll num[]) {
- for (int i = 1; i <= n; i ++) a[i] = num[i];
- }
- void build (int s, int t, int p) {
- if (s == t) {
- node[p].sum = a[s];
- node[p].mi = node[p].lmi = node[p].rmi = min(0LL, a[s]);
- return;
- }
- int mid = (s + t) >> 1;
- build(s, mid, p << 1);
- build(mid + 1, t, p << 1 | 1);
- }
- Node merge (Node &x, Node &y) {
- Node res;
- res.sum = x.sum + y.sum;
- res.lmi = min(x.sum + y.lmi, x.lmi);
- res.rmi = min(x.rmi + y.sum, y.rmi);
- res.mi = min(x.mi, y.mi);
- res.mi = min(res.mi, x.rmi + y.lmi);
- return res;
- }
- void pushup(int p) {
- node[p] = merge(node[p << 1], node[p << 1 | 1]);
- }
- Node query (int l, int r, int s, int t, int p) {
- if (l <= s && t <= r) {
- return node[p];
- }
- int mid = (s + t) >> 1;
- Node res1, res2;
- if (l <= mid) res1 = query(l, r, s, mid, p << 1);
- if (mid < r) res2 = query(l, r, mid + 1, t, p << 1 | 1);
- return merge(res1, res2);
- }
- };
- Segment seg;
- void solve () {
- cin >> n;
- int last = 0;
- cost[0] = 0;
- pre[0] = 0;
- ll mi = 0;
- for (int i = 1; i <= n; i ++) {
- cin >> a[i];
- pre[i] = pre[i - 1] + a[i];
- cost[i] = cost[i - 1] + pre[i];
- mi = min(cost[i] - cost[last], mi);
- // cout << i << ' ' << last << ' ' << mi << endl;
- if (pre[i] > pre[last]) {
- nxt[last] = i;
- lim[i] = mi;
- last = i;
- mi = 0;
- }
- }
- if (last != n) {
- nxt[last] = n;
- lim[n] = mi;
- }
- if (lim[nxt[0]] < 0 || pre[n] < 0) {
- cout << "-1\n";
- return;
- }
- // cout << "debug\n";
- // for (int i = 0; i <= n; i ++) {
- // cout << i << " : " << nxt[i] << ' ' << lim[nxt[i]] << endl;
- // }
- int p = 0;
- ll ans = 0;
- ll sum = 0;
- while (p < n) {
- if (lim[p[nxt]] + sum < 0) {
- ll need = -sum - lim[p[nxt]];
- ll d = (need + pre[p] - 1) / pre[p];
- // cout << d << endl;
- ans += d;
- sum += pre[p] * d;
- }
- sum += cost[nxt[p]] - cost[p];
- ans += nxt[p] - p;
- p = nxt[p];
- // cout << p << ' ' << ans << ' ' << sum << endl;
- }
- cout << ans << endl;
- }
- signed main() {
- ios::sync_with_stdio(false);
- cin.tie(nullptr);
- int _ = 1;
- // cin >> _;
- while(_ --) {
- solve();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement