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
#include <cstdio>
#include <vector>
#include <map>
using namespace std;

#define FOR(i,a,b) for(int (i)=(int)(a); (i)!=(int)(b); ++(i))

int n;
vector<long long int> A;
map<long long int, int> M;

long long int base_extra;
int base_length;

typedef map<long long int, int>::iterator Iter;

int main() {

    // Read input
    scanf("%d", &n);
    A.resize(n);
    int a;
    long long int sum = 0;
    FOR(i,0,n) { scanf("%d", &a); A[i] = (long long int)(a); sum += A[i]; }
    if (sum < 0) { printf("-1\n"); return 0; }

    base_length = 0;
    base_extra = 0;
    M[0] = 0;

    FOR(i,0,n) {

        int best_real_length = -1;
        Iter best_it = M.lower_bound(base_extra);
        if (best_it != M.end()) best_real_length = best_it->second - base_length;

        base_extra -= A[i];
        base_length -= 1;

        Iter inserted_it = M.end();
        if (best_real_length != -1) {
            long long int repr_extra = A[i] + base_extra;
            int repr_length = best_real_length + base_length;

            Iter it = M.find(repr_extra);
            if (it != M.end()) {
                if (it->second > repr_length) {
                    it->second = repr_length;
                    inserted_it = it;
                }
            } else {
                M[repr_extra] = repr_length;
                inserted_it = M.find(repr_extra);
            }
        }

        if (inserted_it != M.end()) {
            Iter it = inserted_it; ++it;
            if (it != M.end() && it->second <= inserted_it->second) {
                M.erase(inserted_it);
            } else {
                while (inserted_it != M.begin()) {
                    it = inserted_it; --it;
                    if (it->second >= inserted_it->second) M.erase(it);
                    else break;
                }
            }
        }
    }

    Iter best_it = M.lower_bound(base_extra);
    if (best_it == M.end()) printf("-1\n");
    printf("%d\n", best_it->second - base_length);
}