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
#include<bits/stdc++.h>
using namespace std;
#define MAXN 500007
typedef long long ll;

ll tab[MAXN], n;
ll partial(int a, int b) {
  if (a) return tab[b] - tab[a-1];
  return tab[b];
}

ll next_pos[MAXN], next_neg[MAXN];

ll solution_from[MAXN], new_sol;
ll length[MAXN];

int main() {
  scanf("%lld", &n);
  for(int i= 0; i <n; i++){
    scanf("%lld", &tab[i]);
  }

  next_pos[n-1] = n;
  next_neg[n-1] = n;

  for(int j = n-2; j >= 0; j--){
    if (tab[j+1] > 0){
      next_pos[j] = j+1;
      next_neg[j] = next_neg[j+1];
    } else if (tab[j+1] < 0){
      next_neg[j] = j+1;
      next_pos[j] = next_pos[j+1];
    } else {
      next_pos[j] = next_pos[j+1];
      next_neg[j] = next_neg[j+1];
    }
  }

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

  if (tab[n-1] < 0){
    printf("-1\n");
    return 0;
  }

  solution_from[n] = 0;

  for(int i = n-1; i>= 0; i--){
    solution_from[i] = n;
 //   ll prev = -10;
//    bool dec = false;
//    printf("\n%d: ", i);
    for(int j = i; j <n && j-i < solution_from[i];){
      if (partial(i, j) >= 0){
        new_sol = j-i + solution_from[j+1];
        solution_from[i] = min(solution_from[i], new_sol);
        /*printf("%d ", new_sol);
        if (prev == new_sol) continue;
        bool side = prev < new_sol;
        if (dec & !side){
          printf("FALSAFDASFD\n");
          printf("%d\n",n);
          for(int k = 0; k < n; k++){
            if (!k) printf("%d ",tab[k]);
            else {
              printf("%d ", tab[k] - tab[k-1]);
            }
          }
          printf("\n");
        }
        if (!side){
          dec = true;
        }
        prev = new_sol;*/
        j = next_neg[j];
      } else {
        j = next_pos[j];
      }
    }
    //printf("%d: %d\n", i, solution_from[i]);
  }
  printf("%lld\n", solution_from[0]);

}