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
#include <cstdio>
#include <vector>
#include <algorithm>
#include <iostream>
#include <cstring>

using namespace std;

#define f first
#define s second

const int MAXN = 5e5 + 13;
const int MAXM = 1024 * 1024 + 3;

int dp[MAXN];
int tree[MAXM];
int skal[MAXN];
long long t[MAXN];
long long pref[MAXN];

int szukaj(int v, int x, int y, int l) {
    if (y < l)
        return -1;
    if (x >= l)
        return tree[v];
    return max(szukaj(v * 2, x, (x + y) / 2, l), szukaj(v * 2 + 1, (x + y) / 2 + 1, y, l));
}

void akt(int v, int war) {
    while (v) {
        tree[v] = max(tree[v], war);
        v /= 2;
    }
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    vector<pair<long long, int> > vec;
    cin >> n;
    for (int i = 1; i <= n; i++) {
        cin >> t[i];
        pref[i] = pref[i - 1] - t[i - 1];
        vec.emplace_back(pref[i], i);
    }
    vec.emplace_back(pref[n] - t[n], n + 1);
    sort(vec.begin(), vec.end());
    int x = 1;
    skal[vec[0].s] = 1;
    for (int i = 1; i <= n; i++) {
        if (vec[i].f != vec[i - 1].f)
            x++;
        skal[vec[i].s] = x;
    }
    memset(tree, -1, sizeof(tree));
    int pot = 1;
    while (pot < x)
        pot *= 2;
    dp[0] = -1;
    for (int i = 1; i <= n; i++) {
        if (i == 1 || dp[i - 1] != -1)
            akt(skal[i] + pot - 1, dp[i - 1] + 1);
        dp[i] = szukaj(1, 1, pot, skal[i + 1]);
    }
    if (dp[n] == -1)
        cout << -1;
    else
        cout << n - 1 - dp[n];
    return 0;
}