Submission #946398

#TimeUsernameProblemLanguageResultExecution timeMemory
946398Sokol080808Candies (JOI18_candies)C++17
100 / 100
651 ms29720 KiB
#define _GLIBCXX_DEBUG

#include <bits/stdc++.h>

using namespace std;

#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()

using ll = long long;
using ull = unsigned long long;
using ld = long double;

const ll INF = 1e18;

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

    int n;
    cin >> n;
    vector<int> a(n + 1);
    for (int i = 1; i <= n; i++) cin >> a[i];

    int mxc = (n + 1) / 2;
    
    set<array<ll, 3>> segs;
    set<array<ll, 3>> best;
    for (int i = 1; i <= n; i++) {
        segs.insert({i, i, a[i]});
        best.insert({a[i], i, i});
    }

    ll ans = 0;
    for (int iteration = 0; iteration < mxc; iteration++) {
        auto it = prev(best.end());
        auto [add, l, r] = *it;
        segs.erase({l, r, add});
        best.erase({add, l, r});
        ans += add;
        cout << ans << '\n';

        if (best.empty()) break;

        auto it2 = segs.lower_bound({l, INF, INF});
        if (it2 == segs.end()) {
            it2 = prev(it2);
            best.erase({(*it2)[2], (*it2)[0], (*it2)[1]});
            segs.erase(it2);
            continue;
        }
        if (it2 == segs.begin()) {
            best.erase({(*it2)[2], (*it2)[0], (*it2)[1]});
            segs.erase(it2);
            continue;
        }
        
        add = -add;
        auto nxt = segs.lower_bound({l, INF, INF});
        if (nxt != segs.end()) {
            add += (*nxt)[2];
            r = (*nxt)[1];
            best.erase({(*nxt)[2], (*nxt)[0], (*nxt)[1]});
            segs.erase(nxt);
        }
        auto prv = segs.lower_bound({l, INF, INF});
        if (prv != segs.begin()) {
            prv = prev(prv);
            add += (*prv)[2];
            l = (*prv)[0];
            best.erase({(*prv)[2], (*prv)[0], (*prv)[1]});
            segs.erase(prv);
        }

        segs.insert({l, r, add});
        best.insert({add, l, r});
    }

    return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...