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
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,Suma,T[1000005];
vector< pair<int,int> > v,K,vnew;
main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(NULL);
    cout.tie(NULL);
    cin >> n;
    for (int i = 1 ; i <= n ; i++)
    {
        cin >> T[i];
        Suma += T[i];
        if(T[i] != 0)
            K.push_back({T[i],i});
    }
    if (Suma < 0)
    {
        cout << -1;
        return 0;
    }
    v.push_back({K[0].first,0});
    for (int w = 1 ; w < K.size() ; w++)
    {
            int mini = INT_MAX;
            for (int i = 0 ; i < v.size() ; i++)
            {
                if(i >= 500 && i <= v.size() - 500 && v.size() >= 4000)
                {
                    if(v[i].first >= 0)
                        mini = min(mini,v[i].second);
                }
                else
                {
                    if(v[i].first > 0)
                        vnew.push_back({v[i].first + K[w].first,K[w].second - K[w-1].second+ v[i].second});
                    if(v[i].first >= 0)
                        mini = min(mini,v[i].second);
                    else
                        vnew.push_back({v[i].first + K[w].first,K[w].second - K[w-1].second+ v[i].second});
                }
            }
            if(mini != INT_MAX)
                vnew.push_back({K[w].first,mini});
            v = vnew;
            vnew.clear();
    }
    int wynik = INT_MAX;
    for (int i = 0 ; i < v.size() ; i++)
    {
        if(v[i].first >= 0)
            wynik = min(wynik,v[i].second);
    }
    cout << wynik;
}