1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <bits/stdc++.h>

using namespace std;
long long int a, b[505000], w[500500], poc, kon, s, sum[500050];
vector<int> q;
int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin >> a;
    for (int i = 0; i < a; i++)
    {
        cin >> b[i];
        sum[i + 1] = b[i] + sum[i];
    }

    if (b[0] >= 0)
    {
        q.push_back(0);
        w[0] = 0;
    }
    else
    {
        w[0] = 1e9;
    }

    for (int i = 1; i < a; i++)
    {
        if (sum[i + 1] - sum[0] < 0)
        {
            w[i] = 1e9;
        }
        else
        {

            while (q.size()>0)
            {
                if (w[q[q.size() - 1]] + i - q[q.size() - 1] - 1 >= w[i - 1])
                {
                    if (b[i] > sum[i + 1] - sum[q[q.size() - 1]])
                    {
                        q.pop_back();
                    }
                    else
                    {
                        q.push_back(i - 1);
                        break;
                    }
                }
                else
                {
                    break;
                }
            }
            if (!q.size())
            {
                q.push_back(i - 1);
            }

            w[i] = i;
            
              //  cout << "GOÓWNO" << endl;
                poc = 0;
                kon = q.size()-1;
                s = (poc + kon + 1) / 2;
                while (poc < kon)
                {
                    //cout << poc << " " << kon << " " << s << " " << q[s] << endl;
                    if (sum[i + 1] - sum[q[s] + 1] >= 0)
                    {
                        poc = s;
                    }
                    else
                    {
                        kon = s - 1;
                    }
                    s = (poc + kon + 1) / 2;
                }
                if (sum[i + 1] - sum[q[poc] + 1] >= 0)
                {
                    w[i] = min(w[q[s]] + i - q[s] - 1, w[i]);
                }
            
        }
      //  cout << w[i] << endl;
    }
    cout << w[a - 1] << "\n";
    return 0;
}