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>

using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    int N, wartosc, suma, droga=0, j, razem=0;
    vector <pair <int, int>> tablica;

    cin >> N;

    for (int i=0; i < N; i++) {
        cin >> wartosc;
        if (wartosc) {
            tablica.push_back({wartosc, i});
            razem += wartosc;
        }
    }

    if (razem < 0) {
        cout << "-1";
        return 0;
    }

    for (int i=0; i < tablica.size(); i++) {
        if (tablica[i].first < 0) {
            suma = tablica[i].first;
            j = 0;
            while (suma < 0) {
                if (i - j < 0)
                    break;
                if (tablica[i - j].first > 0) {
                    suma += tablica[i - j].first;
                    droga += tablica[i - j + 1].second - tablica[i - j].second;
                }
                j++;
            }
            j = 0;
            while (suma < 0) { 
                if (i + j >= tablica.size())
                    break;
                if (tablica[i + j].first > 0) {
                    suma += tablica[i + j].first;
                    droga += tablica[i - j].second - tablica[i - j + 1].second;
                }
                j++;
            }
        }
    }

    cout << droga;

    return 0;
}