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
#include <bits/stdc++.h>
using namespace std;

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

    int n;
    cin >> n;
    vector<int> a(n);
    for (auto& x : a) {
        cin >> x;
    }

    set<pair<long long, int>, greater<pair<long long, int>>> dp;
    dp.emplace(0, 0);

    long long sum = 0;
    int last_result = 0;
    for (int i = 0; i < n; i++) {
        sum += a[i];

        auto it = dp.lower_bound(make_pair(sum, numeric_limits<int>::max()));
        auto result = (it == dp.end() ? numeric_limits<int>::max() : it->second + i);

        if (it != dp.end()) {
            auto it_me = dp.emplace(sum, result - (i + 1)).first;
            while (it_me != dp.begin()) {
                --it_me;
                if (it_me->second >= result - (i + 1)) {
                    it_me = dp.erase(it_me);
                } else {
                    break;
                }
            }
        }

        last_result = result;
    }

    cout << (abs(last_result) > n ? -1 : last_result) << "\n";
}