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
#include <bits/stdc++.h>

#define fi first
#define se second
#define pb push_back
using namespace std;

typedef long long ll;
typedef pair<int, int> pii;

const int maxn = 500005;

int dp[maxn];

ll tab[maxn];

int main()
{
    ios_base::sync_with_stdio(0);

    int n;
    cin >> n;

    for (int i = 1; i <= n; i++)
        cin >> tab[i];

    for (int i = 1; i <= n; i++) {
        if (tab[i] == 0) {
            dp[i] = dp[i - 1];
            continue;
        }

        ll fab = 0;
        ll elek = 0;

        dp[i] = -1;
        for (int j = i; j >= 1; j--) {
            if (tab[j] < 0)
                fab -= tab[j];
            else if(tab[j] > 0)
                elek += tab[j];
            
            if (elek >= fab && dp[j - 1] != -1) {
                int wyn = dp[j - 1];
                if (fab != 0)
                    wyn += i - j;
                if (dp[i] == -1 || dp[i] > wyn)
                    dp[i] = wyn;
            }
        }

    }

    for (int i = 1; i <= n; i++) {
        //cout << i << ": " << tab[i] << " " << dp[i] << "\n";
    }

    cout << dp[n] << "\n";

    return 0;
}