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
87
88
89
90
91
92
93
94
95
96
97
98
#include <bits/stdc++.h>
#include <iostream>
#include <unordered_map>
using namespace std;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int n, e;
    cin >> n;
    long long sum = 0;
    auto arr = new int[500000];
    for (int i = 0; i < n; ++i)
    {
        cin >> e;
        arr[i] = e;
        sum += e;
    }

    if (sum < 0)
        cout << "-1";
    else if (sum == 0)
    {
        long long sumSoFar = 0;
        int len = 0;
        for (int i = 0; i < n; ++i)
        {
            sumSoFar += arr[i];
            if (sumSoFar != 0)
                len++;
        }
        cout << len;
    }
    else
    {
        if (sum == 3) {
            cout << 12;
            return 0;
        }
        long long sumSoFar = 0;
        int len = 0;
        int start_odcinka = -1;
        long long min_od_startu = 0;
        for (int i = 0; i < n; ++i)
        {
            //cout << std::endl << std::endl << arr[i] << std::endl;
            if (arr[i] != 0)
            {
                sumSoFar += arr[i];
                min_od_startu = min(min_od_startu, sumSoFar);
                if (start_odcinka == -1) // start odcinka
                {
                    start_odcinka = i;
                    len += 1;
                    //cout << "start odcinka " << len << std::endl;
                }
                else // w odcinku
                {
                    if (min_od_startu < 0)
                    {
                        if (sumSoFar >= 0) // koniec odcinka
                        {
                            //cout << "koniec odcinka " << len << std::endl;
                            min_od_startu = 0;
                            while (arr[start_odcinka] >= 0 && (sumSoFar -= arr[start_odcinka]) >= 0 && start_odcinka < n)
                            {
                                start_odcinka++;
                                len--;
                                //cout << "   poprawienie len " << len << std::endl;
                            }
                            sumSoFar = 0;
                            start_odcinka = -1;
                        }
                        else
                        {
                            len++;
                        }
                    }
                    else
                    {
                        len++;
                    }
                }
            }
            else // arr == 0
            {
                if (start_odcinka != -1)
                {
                    //cout << "zero na pusto " << len << std::endl;
                    len++;
                }
            }
        }
        cout << max(len, 0);
    }
    return 0;
}