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
#include <bits/stdc++.h>
using namespace std;
const int MX=500500;
int n,m,i,a[MX];
long long inf,cur,curf,b[MX],allb[MX];

struct Fenwick {
  long long a[MX],le[MX],ri[MX];

  void init() {
    memset(a,100,sizeof(a));
    memset(le,100,sizeof(le));
    memset(ri,100,sizeof(ri));
    inf=a[0];
  }

  void updmin(int x, long long v) {
    if (v>=a[x]) return;
    a[x]=v;    
    for (int i=x; i>0; i&=i-1) le[i]=min(le[i],v);
    for (; x<=m; x=(x<<1)-(x&(x-1))) ri[x]=min(ri[x],v);
  }

  long long fndmin(int x) {
    long long res=a[x];
    int nxt,i;
    for (i=1; ; i=nxt) {
      nxt=(i<<1)-(i&(i-1));
      if (nxt>x) break;
      res=min(res,le[i]);
    }
    res=min(res,a[i]);
    for (i=x; ; i=nxt) {
      nxt=(i&(i-1));
      if (nxt<1) break;
      res=min(res,ri[i]);
    }
    return min(res,a[i]);
  }

} fenw;

int main() {
  scanf("%d",&n);
  for (i=1; i<=n; i++) {
    scanf("%d",&a[i]);
    b[i]=b[i-1]+a[i];
    allb[i]=b[i];
  }
  sort(allb,allb+n+1);
  m=unique(allb,allb+n+1)-allb;
  fenw.init();
  fenw.updmin(lower_bound(allb,allb+m,0)-allb+1,cur=0);
  for (i=1; i<=n; i++) {
    b[i]=lower_bound(allb,allb+m,b[i])-allb+1;
    curf=min(inf,fenw.fndmin(b[i])+i-1);
    if (i>0) {
      if (a[i]<0) cur=curf; else cur=min(cur,curf);
    }
    if (curf<inf) fenw.updmin(b[i],cur-i);
  }
  printf("%lld\n",(cur>=inf)?-1LL:cur); 
  return 0;
}