Submission #934569

#TimeUsernameProblemLanguageResultExecution timeMemory
934569PanndaWorst Reporter 4 (JOI21_worst_reporter4)C++17
100 / 100
291 ms97360 KiB
#include <bits/stdc++.h>
using namespace std;

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

    int n;
    cin >> n;
    vector<int> a(n), h(n), c(n);
    for (int u = 0; u < n; u++) {
        cin >> a[u] >> h[u] >> c[u];
        a[u]--;
    }

    vector<map<int, long long>> f(n);
    auto add = [](map<int, long long> &x, map<int, long long> &y) {
        if (y.size() > x.size()) swap(x, y);
        for (auto [h, c] : y) x[h] += c;
    };
    auto fix = [](map<int, long long> &x, int h, long long c) {
        x[h] += c;
        auto it = x.lower_bound(h);
        while (it != x.begin()) {
            it = prev(it);
            if (it->second <= c) {
                c -= it->second;
                it = x.erase(it);
            } else {
                it->second -= c;
                break;
            }
        }
    };

    vector<int> deg(n, 0);
    queue<int> que;
    for (int u = 0; u < n; u++) deg[a[u]]++;
    for (int u = 0; u < n; u++) if (!deg[u]) que.push(u);

    while (!que.empty()) {
        int u = que.front();
        que.pop();
        fix(f[u], h[u], c[u]);
        add(f[a[u]], f[u]);
        if (!--deg[a[u]]) que.push(a[u]);
    }

    long long res = 0;
    for (int u = 0; u < n; u++) {
        if (deg[u] > 0) {
            map<int, long long> sum;
            sum[h[u]] += c[u];
            deg[u] = 0;
            for (int v = a[u]; v != u; v = a[v]) {
                add(f[u], f[v]);
                sum[h[v]] += c[v];
                deg[v] = 0;
            }
            for (auto [h, c] : sum) {
                fix(f[u], h, c);
            }
            for (auto [h, c] : f[u]) {
                res += c;
            }
        }
    }

    cout << accumulate(c.begin(), c.end(), 0LL) - res << '\n';
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...