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
#include <cstdio>
#include <vector>
#include <set>

std::vector<std::pair<long long int, long long int> > acu;

struct Entry {
    Entry(long long int iprice, long long int ipower, int position) :
        iprice(iprice), ipower(ipower), position(position) 
    {
    }

    long long int getPower() const {
        return ipower + acu.back().second - acu[position].second;
    }

    long long int getPrice() const {
        return iprice + acu.back().first - acu[position].first;
    }

    bool operator<(const Entry &lhs) const {
        return getPower() < lhs.getPower();
    }

private:
    long long int iprice;
    long long int ipower;
    int position;
};

std::multiset<Entry> results;

int getCheapest() {
    auto it = results.lower_bound(Entry(0,0,acu.size()-1));
    if (it != results.end() && it->getPower() >= 0) {
        return it->getPrice();
    }

    return -1;
}

void addEntry(const Entry &entry) {
    auto it = results.upper_bound(entry);
    --it;
    while (it != results.end() && it->getPower() <= entry.getPower() && it->getPrice() >= entry.getPrice()) {
        it = results.erase(it);
        if (it != results.begin()) {
            --it;
        }
    }

    it = results.lower_bound(entry);
    if (it != results.end()) {
        if (it->getPower() == entry.getPower() && it->getPrice() < entry.getPrice()) {
            return;
        }

        if (it->getPower() > entry.getPower() && it->getPrice() <= entry.getPrice()) {
            return;
        }
    }

    results.insert(entry);
}

int main() {
    int N;
    int distance = 0;

    acu.push_back(std::make_pair(0,0));
    results.insert(Entry(0,0,0));
    
    scanf("%d",&N);
    for (int i=0; i<N; ++i) {
        long long int a;
        scanf("%lld", &a);

        distance++;
        if (a != 0) {
            long long int cheapest = getCheapest();
            acu.push_back(std::make_pair(acu.back().first+distance, acu.back().second+a));
            if (cheapest >= 0) {
                addEntry(Entry(cheapest, a, acu.size()-1));
            }
            distance = 0;
/*
            for (auto &x: results) {
                printf("%lld %lld\n", x.getPrice(), x.getPower());
            }
            printf("xxx\n");
*/
        }
    }

    printf("%d\n", getCheapest());
    return 0;
}